CORE SPECIFICATION

Smart School Management System — Architecture & Developer Manual

LARAVEL 12 + VUE 3 + STANCL
SECTION 00 • FOUNDATION

Architecture & Multi-Tenancy Engine

This platform is a multi-tenant School Management SaaS built with Laravel 12 and Vue 3 (Inertia.js). It uses one shared database, with tenant-owned records isolated by tenant ID and domain-based tenancy context powered by Stancl Tenancy v3.

[CENTRAL DATABASE]
  • • tenants: Tenant ID, school profile, status, plan_id, db credentials
  • • domains: Subdomains and custom domains linked to tenant
  • • plans: Subscription tiers, limits (students, teachers, staff), pricing in BDT
  • • subscriptions: School subscription periods, payment status, renewals
  • • platform_invoices: Central billing invoices for schools
  • • tenant_sms_logs: Platform-wide SMS allocations and consumption audit
  • • database_backup_logs: Central database snapshot records
  • • activity_log: Global super administrator audit trail
[TENANT DATABASE (Per School)]
  • • users: School admin, teachers, students, parents, staff
  • • students & student_academics: Enrolled pupils, admission numbers, rolls
  • • classes, sections, subjects: Academic structural hierarchy
  • • attendances & biometric_devices: Physical punches, morning statuses
  • • fee_categories, structures, invoices: Student billing & SSLCommerz
  • • exams, exam_subjects, marks: Grading, report cards, GPA scales
  • • books & book_issues: Library inventory, active loans, fines
  • • payrolls & expenses: Staff compensations and operating vouchers
TENANT IDENTIFICATION & ROUTING LIFECYCLE:

1. Incoming HTTP request hits Nginx reverse proxy.

2. Central domains (e.g. localhost, smartschool.com) match Central Route Collection in routes/web.php.

3. Tenant subdomains (e.g. ideal-school.smartschool.com) trigger Stancl\Tenancy\Middleware\InitializeTenancyByDomain in routes/tenant.php.

4. Tenant connection automatically dynamically connects to database tenant_{id}.

5. If domain is unmapped, system intercepts with custom 404 Inertia error handler.

SECTION 01 • ENGINEERING STACK

Technology Stack & Architectural Patterns

Layer / Tool Version / Technology Architectural Responsibility
Backend Framework Laravel 12 (PHP 8.3+) Routing, ORM, multi-tenancy pipelines, security, authorization gates.
Frontend Engine Vue 3 + Inertia.js 2 Single Page Application (SPA) experience without decoupling backend controllers.
Styling & UI Tailwind CSS 3.4 Responsive utility-first layout, dark/light theme, typography.
Multi-Tenancy Stancl Tenancy 3.8 Domain resolver, automatic tenant DB switching, filesystem scoping.
Authorization Spatie Laravel Permission 6 Role-Based Access Control (RBAC), granular permission matrices.
Audit Logging Spatie Activitylog 4 Immutable audit trail of actions performed by administrators and staff.
PDF Generation Barryvdh DomPDF 3 Server-side rendering of ID cards, admit cards, report cards, routine timetables.
Payment Gateway SSLCommerz Hosted API Online payment processing in Bangladeshi Taka (৳ BDT) with IPN callback.
Hardware Biometrics ZKTeco Push Protocol Hardware biometric time clocks, device heartbeat, punch log aggregation.
[ACTION PATTERN ARCHITECTURE]:

To maintain slim controllers, business logic is encapsulated inside dedicated single-responsibility Action classes located in app/Actions/Tenant/. For example, enrolling an applicant is performed by CreateStudentAction, settling fees by SettleSslCommerzPaymentAction, and generating routine timetables by SaveRoutineAction.

SECTION 02 • ROLE SPECIFICATION

Role: Super Admin (Central SaaS Platform)

ROLE: super_admin DATABASE: Central MySQL ROUTE PREFIX: /admin, /tenants, /plans

The Super Administrator oversees the entire SaaS infrastructure. They manage tenant school onboarding, approval workflows, subscription billing, plan limits, SMS credits, central backups, and platform-level audit logs.

1. SCHOOL ONBOARDING & TENANT LIFECYCLE MANAGEMENT

Path: /tenants & /approvals • Controller: TenantController, TenantApprovalController

  • • School Registration: Public schools register via /register-school specifying requested subdomain, admin contact, and subscription plan.
  • • Approval Workflow: Pending applications appear in Central Approvals. Super Admin reviews school credentials and clicks [Approve].
  • • Automated Provisioning: Approval triggers JobPipeline executing CreateDatabase followed by MigrateDatabase and seeding tenant roles and initial school administrator.
  • • Tenant Status: Statuses: pending, active, suspended, banned. Suspending instantly cuts off tenant subdomain access.
  • • Impersonation: Super Admin can click [Impersonate] to securely authenticate into any school's administrative panel without asking for passwords.
2. SAAS PLANS, QUOTAS & PACKAGING

Path: /plans • Controller: PlanController • Model: App\Models\Plan

  • • Configure plans with student limits (e.g. 300, 1000, 5000) and staff limits (e.g. 30, 100, 500).
  • • Dual billing cycles: price_monthly and price_yearly stored in BDT (৳).
  • • Feature toggles: Biometric attendance enabled, SMS gateway enabled, White-label portal enabled.
3. CENTRAL SMS ALLOCATION & USAGE AUDIT

Path: /sms • Controller: TenantSmsController • Model: App\Models\TenantSmsLog

  • • Super admin allocates SMS credit packages to specific schools.
  • • Tracks real-time sent count, failed count, recipient phone numbers, and gateway API responses across all schools.
4. CENTRAL PLATFORM BACKUPS & RECOVERY

Path: /backups • Controller: CentralBackupController • Rate-limited: throttle:10,1

  • • Generate full platform database dumps on-demand.
  • • Create platform database backups containing central and tenant records.
  • • Secure rate-limited download stream with zip file integrity verification.
SECTION 03 • ROLE SPECIFICATION

Role: School Admin (Tenant Administration)

ROLE: school_admin, admin DATABASE: Tenant Database ROUTE PREFIX: /admin, /tenant/*

The School Admin has full control over the individual institution's operational ecosystem. They manage academics, students, teachers, fee structures, examinations, attendance hardware, accounting, payroll, and website portfolio.

ADMINISTRATIVE DASHBOARD & GEOGRAPHIC ANALYTICS

Path: /admin/dashboard • Controller: Tenant\DashboardController

  • • Regional Demographic Heatmap: Visual interactive SVG map of the 8 administrative divisions of Bangladesh (Dhaka, Chittagong, Rajshahi, Khulna, Barishal, Sylhet, Rangpur, Mymensingh) showing live student enrollment distribution.
  • • Faith & Religion Breakdown: Live enrollment distribution across Muslim, Hindu, Buddhist, Christian, and Other.
  • • Device Platform Share: Real-time platform tracking (Desktop, Mobile, Tablet).
  • • Today's Attendance Status Share: Donut chart of Present, Absent, Late, and Half-day students.
  • • Financial Summary: Total billed, total collected (৳), outstanding dues, and 30-day collection velocity.
STUDENT LIFECYCLE & PROMOTION ENGINE

Path: /admin/students • Controller: StudentController • Action: PromoteStudentAction

  • • Full Student Directory with server-side searchable data table and export to Excel/CSV.
  • • Detailed 360-degree Profile: attendance history (MySQL aggregated), paid invoices, active book loans, guardian contact.
  • • Bulk Promotion Engine: Promotes entire classes from one Academic Year to the next (e.g., Class 1 to Class 2) with automated roll reassignment while archiving previous academic histories in student_academics.
FEE STRUCTURES, INVOICING & PAYMENT GATEWAY

Path: /admin/fees • Controller: FeeController • Action: GenerateClassInvoicesAction

  • • Fee Categories: Tuition, Admission, Exam, Transport, Lab, Session, Development.
  • • Bulk Class Invoice Generator: Emits customized invoices for every student in a class with 1-click.
  • • Payment Collection: Supports Cash/Bank counter collection (with partial payments) or Online Checkout via SSLCommerz.
  • • Automated Payment Reminders: Evaluates due dates and triggers automated SMS/Email reminders to parents.
EXAMINATIONS, MARKS & REPORT CARDS

Path: /admin/exams • Controller: ExamController • Policy: ExamPolicy

  • • Configure Exam Types, exam subjects, full marks, and pass marks.
  • • Tab-friendly Marks Entry Grid: Instant score recording, absence toggle, automated grade points (GPA 5.0 scale).
  • • Publish Privacy Lock: Results remain strictly invisible to students and parents until the School Admin explicitly toggles is_published = true.
  • • Official PDF Report Card generation via DomPDF.
SECTION 04 • ROLE SPECIFICATION

Role: Teacher

ROLE: teacher GUARD: web PERMISSIONS: manage_attendance, manage_marks, view_routines

Teachers manage academic instruction, daily attendance, examination marks entry, routine timetables, and their personal leave applications.

[ATTENDANCE RECORDING]

Teachers can record daily morning attendance and period-wise attendance for their assigned classes. Quick toggles: Present, Late, Absent, Half Day.

Routes: /admin/morning, /admin/attendance/students

[EXAM MARKS ENTRY]

Teachers can select Exam, Class, and Subject to open the Marks Entry Matrix. Marks are validated against subject full mark with auto GPA calculation.

Routes: /admin/exams/marks-entry

[CLASS ROUTINES & TIMETABLES]

Teachers have full access to view weekly period routines for their assigned subjects and download printable landscape PDF timetables.

Routes: /admin/routines, /admin/routines/export/pdf

[LEAVE APPLICATIONS]

Teachers can apply for Sick Leave, Casual Leave, or Earned Leave with date range and reason. Balance automatically updates upon admin approval.

Routes: /admin/leaves • Action: ApplyLeaveAction

SECTION 05 • ROLE SPECIFICATION

Role: Student

ROLE: student GUARD: web PORTAL ROUTE: /student/dashboard

Enrolled students log into a personalized Student Portal. They can track attendance records, view class timetables, see examination schedules, download published report cards, view outstanding fee dues, and pay online.

[1. STUDENT DASHBOARD]:

Displays real-time attendance percentage, today's classes from the routine, upcoming exams, and pending fee alerts.

[2. ATTENDANCE CALENDAR]:

Path: /student/attendance • Visual monthly calendar color-coded by Present, Absent, Late, or Holiday with total percentages.

[3. EXAMS & REPORT CARDS]:

Path: /student/exams • Access to exam dates and syllabus. Student can download official PDF Report Card only when is_published = true.

[4. FEE PORTAL & ONLINE PAYMENT]:

Path: /student/fees • Lists all issued invoices, paid amounts, and due balances. Clicking [Pay Online] redirects to SSLCommerz gateway to pay via bKash, Nagad, Rocket, or Visa/Mastercard.

SECTION 06 • ROLE SPECIFICATION

Role: Parent / Guardian

ROLE: parent GUARD: web PORTAL ROUTE: /parent/dashboard

The Parent Portal features multi-child switching, enabling parents with multiple children enrolled in the same school to monitor each ward independently under a single user account.

[MULTI-CHILD SELECTOR]

A switcher on top of the dashboard toggles between children. When selected, all academic progress, attendance stats, and fee invoices dynamically refresh for that child.

[LIVE ATTENDANCE ALERTS]

Parents see real-time whether their child arrived at school or was marked absent. The system dispatches SMS notifications to the parent's mobile on absence.

[REPORT CARD DOWNLOAD]

Parents can view published exam gradebooks and download the official signed PDF report card for each term.

[ONE-CLICK FEE PAYMENT]

Parents can review monthly tuition bills and complete payment securely via SSLCommerz with instantaneous digital receipt issuance.

SECTION 07 • ROLE SPECIFICATION

Role: Specialized Staff (Accounts, Library, Office)

ROLES: accountant, librarian, staff, receptionist RBAC: Spatie Permission Matrix
ACCOUNTANT (role: accountant)

Permissions: manage_fees, collect_fees, manage_accounts, manage_payroll.

  • • Collects cash/cheque counter fees from students and prints official payment receipts.
  • • Runs monthly bulk class invoice generation.
  • • Tracks expense categories and records operating expense vouchers.
  • • Executes monthly payroll batch generation and generates teacher/staff payslips.
LIBRARIAN (role: librarian)

Permissions: manage_library, view_library.

  • • Catalogues books with Title, Author, ISBN, Publisher, Shelf location, and total copies.
  • • Issues books to students or staff with automated due-date calculation.
  • • Processes book returns and computes overdue delay fines.
RECEPTIONIST & OFFICE STAFF (role: receptionist, staff)

Permissions: manage_admissions, view_students.

  • • Reviews incoming online admission applications and updates preliminary statuses.
  • • Assists with walk-in parent inquiries and document uploads.
SECTION 18 • DATA FLOW ARCHITECTURE

DFD Level 0: Context Data Flow Diagram

The Level 0 context diagram demonstrates the boundary of the Smart School Management SaaS platform and how external entities (Super Admin, School Admin, Teachers, Students, Parents, Payment Gateways, and Biometric Devices) interact with the central system.

flowchart TB SA["Super Administrator (SaaS Owner)"] ADM["School Administrator (Tenant)"] TEA["Teacher"] STU["Student"] PAR["Parent / Guardian"] SSL["SSLCommerz Payment Gateway"] BIO["ZKTeco Biometric Devices"] SMS["SMS Gateway (Alpha / Bulk SMS)"] SYS["Smart School Management SaaS System"] SA -- "1. Plan Setup, Tenant Approvals, SMS Quota" --> SYS SYS -- "2. Billing Invoices, Global Analytics" --> SA ADM -- "3. School Config, Staff, Fees, Exams" --> SYS SYS -- "4. School Reports, Attendance Metrics" --> ADM TEA -- "5. Attendance Marking, Marks Entry" --> SYS SYS -- "6. Timetables, Class Student Lists" --> TEA STU -- "7. View Grades, Fee Invoices, Routine" --> SYS SYS -- "8. Report Cards, Payment Receipts" --> STU PAR -- "9. Tuition Fees, Child Progress Check" --> SYS SYS -- "10. Absence Alerts, Invoices, Results" --> PAR SYS -- "11. Payment Init (BDT)" --> SSL SSL -- "12. IPN Webhook Verification" --> SYS BIO -- "13. Push Protocol Fingerprint Punches" --> SYS SYS -- "14. SMS Broadcast Notification" --> SMS
SECTION 19 • DATA FLOW ARCHITECTURE

DFD Level 1: Multi-Tenancy Architecture & Routing Flow

Decomposition of how the routing layer classifies HTTP requests, identifies tenancy, selects the target database, and enforces authorization gates.

flowchart TD REQ["Incoming Client HTTP Request"] DOM_CHECK{"Is Request Host in Central Domains?"} CENTRAL_ROUTER["Central Route Collection (routes/web.php)"] TENANT_RESOLVER["InitializeTenancyByDomain Middleware"] TENANT_LOOKUP{"Match Domain in Central domains Table?"} ERR_404["Abort 404: School Not Found"] DB_SWITCH["Dynamic DB Connection Switch: tenant_{id}"] TENANT_ROUTER["Tenant Route Collection (routes/tenant.php)"] RBAC_CHECK{"Role & Permission Check (Spatie + Policies)"} ERR_403["Abort 403: Forbidden Access"] CONTROLLER["Execute Controller / Action Class"] RESP["Render Inertia Vue View / Return JSON Response"] REQ --> DOM_CHECK DOM_CHECK -- "YES (e.g. localhost, smartschool.com)" --> CENTRAL_ROUTER CENTRAL_ROUTER --> CONTROLLER DOM_CHECK -- "NO (e.g. ideal.smartschool.com)" --> TENANT_RESOLVER TENANT_RESOLVER --> TENANT_LOOKUP TENANT_LOOKUP -- "NOT FOUND" --> ERR_404 TENANT_LOOKUP -- "FOUND" --> DB_SWITCH DB_SWITCH --> TENANT_ROUTER TENANT_ROUTER --> RBAC_CHECK RBAC_CHECK -- "UNAUTHORIZED" --> ERR_403 RBAC_CHECK -- "AUTHORIZED" --> CONTROLLER CONTROLLER --> RESP
SECTION 20 • DATA FLOW ARCHITECTURE

DFD Level 2: Student Admission & Enrollment Pipeline

Step-by-step logic and data transformations from a prospective student's online application to active student account, guardian linkage, and academic roll assignment.

sequenceDiagram autonumber actor Applicant as Applicant / Parent participant Web as Public School Portal participant AC as AdmissionApplicationController participant DB as Tenant Database actor Admin as School Admin / Receptionist participant Act as CreateStudentAction Applicant->>Web: Submits Admission Form (/admission/apply) Web->>AC: POST Form Data (Applicant info, Guardian, Class) AC->>DB: Insert admission_applications (status: pending) AC-->>Applicant: Application Submitted (Shows Application #) Admin->>AC: View Application Details (/admin/admissions) Admin->>AC: Review Notes & Click [Enroll Student] AC->>Act: execute(application_data) Act->>DB: Check duplicate email / admission_number Act->>DB: Create User record (role: student) Act->>DB: Create Student record Act->>DB: Create Guardian record (role: parent) & link pivot Act->>DB: Insert student_academics (class, section, roll, year) Act->>DB: Update admission_applications (status: enrolled) Act-->>AC: Student Created Successfully AC-->>Admin: Redirect with Student Profile Link
SECTION 21 • DATA FLOW ARCHITECTURE

DFD Level 2: Biometric Hardware & Attendance Engine

Architecture of physical hardware biometric integration alongside daily manual morning attendance recording.

flowchart LR BIO["ZKTeco Biometric Machine"] -- "1. POST /api/biometric/punch" --> PUNCH["ProcessBiometricPunchAction"] PUNCH -- "2. Lookup device_id & biometrics" --> DB_DEV[("biometric_devices")] PUNCH -- "3. Match student / staff ID" --> DB_USER[("users & students")] PUNCH -- "4. Upsert attendance record" --> DB_ATT[("attendances")] TEACHER["Teacher / Admin"] -- "5. Morning Attendance Grid" --> MORN["RecordMorningAttendanceAction"] MORN -- "6. Bulk update status" --> DB_ATT DB_ATT -- "7. If Absent / Late" --> SMS_ENG["SmsNotificationService"] SMS_ENG -- "8. HTTP POST SMS API" --> GATEWAY["External SMS Gateway (BDT)"] GATEWAY -- "9. SMS to Parent Mobile" --> PARENT["Parent Mobile Phone"]
SECTION 22 • DATA FLOW ARCHITECTURE

DFD Level 2: Fees, Invoicing & SSLCommerz Payment Flow

Complete transaction lifecycle from bulk class fee generation to online checkout, IPN webhook validation, and ledger settlement.

sequenceDiagram autonumber actor Admin as School Admin / Accountant participant Gen as GenerateClassInvoicesAction participant DB as Tenant Database actor P as Student / Parent participant Pay as PaymentCheckoutController participant SSL as SSLCommerz Gateway participant Webhook as SslCommerzWebhookController participant Settle as SettleSslCommerzPaymentAction Admin->>Gen: Trigger Monthly Class Billing Gen->>DB: Query fee_structures for Class Gen->>DB: Batch Insert invoices & invoice_items DB-->>P: Invoices Visible in Portal (status: unpaid) P->>Pay: Clicks [Pay Now ৳] on Invoice Pay->>SSL: Init Session (Amount, Currency: BDT, tran_id) SSL-->>P: Redirect to Hosted Payment Page (bKash, Nagad, Cards) P->>SSL: Submits PIN / OTP & Completes Payment SSL->>Webhook: Instant Payment Notification (IPN Webhook) Webhook->>Settle: execute(transaction_data) Settle->>SSL: Server-to-Server Validation (validates amount & BDT currency) Settle->>DB: DB::transaction -> Update invoice status to 'paid' Settle->>DB: Insert payments record Settle-->>P: Instant SMS Payment Confirmation (৳)
SECTION 23 • DATA FLOW ARCHITECTURE

DFD Level 2: Examination, Marks Entry & Report Cards

Workflow detailing how exam structures are set, marks recorded, GPA computed, and unpublished results locked against unauthorized viewing.

flowchart TD ADM["Admin: Create Exam (exam_types, dates, description)"] --> EXAM_DB[("exams table: is_published = false")] SUB["Admin: Define Exam Subjects & Full Marks"] --> EXSUB_DB[("exam_subjects table")] TEA["Teacher / Admin opens Marks Entry Grid"] --> INPUT["Input marks_obtained, is_absent, remarks"] INPUT --> SAVE["SaveExamMarksAction"] SAVE --> CALC["Auto compute grade & grade_point (GPA 5.0)"] CALC --> MARKS_DB[("marks table")] LOCK{"Exam is_published == true?"} MARKS_DB --> LOCK LOCK -- "NO" --> BLOCKED["Students & Parents Blocked (HTTP 403)"] LOCK -- "YES" --> VIEW["Students & Parents can view Report Card"] VIEW --> PDF["DomPDF: Generate Signed Official Report Card PDF"]
SECTION 24 • DATABASE BLUEPRINT

Database Schema & Entity Relationship Architecture

A comprehensive map of all tables, relations, and foreign keys across Central and Tenant database schemas.

[TENANT DATABASE CORE ENTITY RELATIONSHIPS]:
[classes] 1 ──── < [sections]
   │
   ├──── < [class_subjects] > ──── [subjects]
   │
   ├──── < [student_academics] > ──── [students] 1 ──── 1 [users]
   │                                     │
   │                                     ├──── < [student_guardian] > ──── [guardians] 1 ──── 1 [users]
   │                                     │
   │                                     ├──── < [attendances]
   │                                     │
   │                                     ├──── < [invoices] 1 ──── < [invoice_items]
   │                                     │        │
   │                                     │        └──── < [payments]
   │                                     │
   │                                     └──── < [marks] > ──── [exams] 1 ──── < [exam_subjects]
   │
   ├──── < [routines] (day, period, room, subject_id, teacher_id)
   │
   └──── < [fee_structures] > ──── [fee_categories]
                    
SECTION 25 • OPERATIONAL PLAYBOOK

Artisan Commands & Operations Playbook

MIGRATION & TENANT PROVISIONING
# Run all central and tenant schema migrations
php artisan migrate

# Seed platform data and tenant-scoped records
php artisan db:seed
                        
PRODUCTION CACHING (FULL PIPELINE)
# Cache configurations
php artisan config:cache

# Cache routes (with multi-tenant domain constraints)
php artisan route:cache

# Cache Blade templates
php artisan view:cache

# Clear all caches for fresh deployment
php artisan optimize:clear
                        
FRONTEND ASSET COMPILATION
# Build production bundle (Dynamic Async ApexCharts & Vite)
npm run build

# Start local HMR development server
npm run dev
                        
SECTION 26 • CODE STANDARDS

Actions, Policies & Code Conventions

A guide for incoming developers on writing new code adhering to this codebase's architectural integrity.

1. USER MODEL ROLE HELPERS:

Always use the centralized helpers on User model instead of manually checking user_type strings:

$user->isAdmin(), $user->isTeacher(), $user->isStudent(), $user->isParent(), $user->isStaff(), $user->isAccountant(), $user->isLibrarian(), $user->isReceptionist().

2. CURRENCY & LOCALIZATION:

All currency formatting throughout the application must use the official Bangladeshi Taka symbol: ৳ (BDT), never raw dollar ($) signs.

3. POLICY-DRIVEN SECURITY:

Always authorize actions using Laravel Policies registered in app/Policies/Tenant/:

$this->authorize('create', Exam::class); or $this->authorize('view', $invoice);.

4. DATABASE TRANSACTIONS & NOTIFICATIONS:

Never dispatch external HTTP notifications or SMS inside DB::transaction(function() { ... }). Always execute the database mutations first, and dispatch notifications after the transaction successfully commits.