Wednesday, 2 July 2025

Revolutionizing Pharmacy Operations: Point of Sale (POS) Pharmacy Management Systems with Node.js and MySQL

How to create a pharmacy management system using Node.js

How to create a pharmacy management system using Node.js

Introduction

In today's fast-paced healthcare landscape, pharmacies are more than just dispensing centers; they are vital hubs for community health. Managing the intricate operations of a pharmacy, from inventory and sales to patient records and regulatory compliance, can be a daunting task. This is where a robust Pharmacy Management System (PMS) becomes indispensable. A well-designed PMS streamlines workflows, enhances efficiency, reduces errors, and ultimately improves patient care. This blog post delves into the creation of a modern Pharmacy Management System leveraging the power of Node.js, the flexibility of Express.js, and the reliability of MySQL.

Traditional pharmacy operations often grapple with manual processes, leading to inefficiencies, potential for human error, and a lack of real-time insights. Imagine the challenges of tracking hundreds, if not thousands, of medicine SKUs, managing diverse supplier relationships, processing countless prescriptions daily, and generating accurate sales reports – all without a centralized, automated system. These challenges underscore the critical need for a digital transformation in pharmacy management. A PMS not only automates these tasks but also provides a comprehensive overview of the entire operation, empowering pharmacists and administrators to make data-driven decisions and focus more on patient engagement.

Our exploration will highlight how a PMS built with this powerful technology stack can revolutionize daily pharmacy tasks. Node.js, with its asynchronous, event-driven architecture, is perfectly suited for building scalable and high-performance backend applications. Express.js, a minimalist web framework for Node.js, provides the necessary tools for creating robust APIs and handling routing efficiently. Complementing this, MySQL stands as a leading open-source relational database, renowned for its stability, speed, and widespread adoption, making it an ideal choice for storing critical pharmacy data securely. Together, these technologies form a formidable foundation for a system that is not only powerful and efficient but also adaptable to the evolving needs of the pharmaceutical industry. We will explore the core modules of such a system, detailing the features and functionalities that empower both administrative staff and dispensing pharmacists, ultimately contributing to a more organized, profitable, and patient-centric pharmacy environment.

Online Demo








Admin Module: The Command Center

The Admin Module serves as the central control panel for the entire Pharmacy Management System. It provides administrators with a comprehensive overview of operations and the tools necessary to manage the pharmacy effectively. This module is designed for oversight, configuration, and strategic decision-making, ensuring smooth and efficient functioning across all departments.

Dashboard: Your Operational Overview

Upon logging in, the administrator is greeted by an intuitive dashboard that offers a real-time snapshot of key performance indicators. This centralized view eliminates the need to sift through disparate reports, providing immediate insights into the pharmacy's health. Key metrics displayed typically include:

  • Total Pharmacists: A quick count of registered pharmacists, allowing for easy workforce management.
  • Total Medical Companies: An overview of the number of suppliers and pharmaceutical companies the pharmacy collaborates with.
  • Total Medicines: A comprehensive tally of all unique medicine types stocked, indicating the breadth of the pharmacy's inventory.
  • Sales Summary: Crucial financial insights broken down by periods such as today, yesterday, and the last 7 days, enabling administrators to track daily and weekly revenue trends.
  • Total Invoices: A count of all transactions processed, offering a measure of operational volume.

This dashboard acts as a strategic tool, enabling administrators to quickly identify trends, assess performance, and pinpoint areas that may require immediate attention, fostering proactive management.

Invoice Search: Rapid Transaction Retrieval

Efficient access to past transactions is paramount for customer service, auditing, and dispute resolution. The Invoice Search feature within the Admin Module allows administrators to swiftly locate any invoice using flexible search criteria. Whether a customer inquires about a past purchase or an audit requires specific transaction details, the system facilitates rapid retrieval based on:

  • Invoice Number: Direct lookup using the unique identifier assigned to each transaction.
  • Mobile Number: Convenient search by customer's registered mobile number, ideal for quick customer service inquiries.

This functionality significantly reduces the time spent on manual record-keeping and enhances the overall efficiency of customer support and financial reconciliation processes.

Medicine Inventory: Precision Stock Management

Managing pharmaceutical inventory is a complex task that directly impacts patient safety and business profitability. The Medicine Inventory feature provides administrators with granular control and visibility over stock levels. This includes:

  • Real-time Stock View: An up-to-the-minute display of the remaining quantity for each medicine.
  • Low Stock Alerts: Automated notifications or visual cues for medicines falling below predefined minimum stock levels, preventing stockouts and ensuring continuous availability of essential drugs.

By offering precise control and proactive alerts, this feature minimizes waste, optimizes ordering processes, and ensures that the pharmacy is always well-stocked to meet patient demands, thereby enhancing operational continuity and patient satisfaction.

Pharmacy Companies: Supplier Relationship Management

Effective management of supplier relationships is crucial for a consistent and reliable supply chain. The Pharmacy Companies section allows administrators to maintain a comprehensive database of all pharmaceutical companies and suppliers. This includes the ability to:

  • Add New Companies: Easily onboard new suppliers with all relevant details.
  • Update Existing Details: Modify company information, contact persons, and other critical data as needed.

This centralized repository simplifies procurement, ensures accurate record-keeping, and facilitates better communication and negotiation with suppliers, contributing to a more resilient supply chain.

Medicines: Comprehensive Drug Database

The core of any pharmacy lies in its medicine catalog. The Medicines management feature provides administrators with a robust system to maintain an accurate and detailed database of all drugs. This includes functionalities to:

  • Add New Medicine Records: Input details for new drugs, including generic names, dosages, forms, and pricing.
  • Update Existing Medicine Records: Modify information for existing medicines, such as changes in pricing, stock levels, or descriptive details.

This ensures that all medicine-related information is current and accurate, supporting efficient dispensing, pricing, and inventory management, and ultimately contributing to patient safety and regulatory compliance.

Pharmacists: Workforce Management

Managing the pharmacy's human resources, particularly the pharmacists, is a key administrative function. This module provides tools to oversee the pharmacist workforce, including:

  • Add New Pharmacists: Register new pharmacists with their credentials and roles.
  • Update Pharmacist Records: Modify personal details, contact information, and employment status.
  • Activate/Deactivate Accounts: Control access to the system for individual pharmacists, crucial for security and managing staff changes.

This feature ensures that all pharmacist data is securely managed, facilitating smooth onboarding, offboarding, and ongoing personnel administration.

Reports: Data-Driven Insights

Data is a powerful asset, and the Reports section transforms raw transactional data into actionable insights. Administrators can generate various types of reports to analyze sales performance, identify trends, and support strategic planning. Key reports typically include:

  • Sales Reports by Date Range: Analyze revenue and transaction volumes over specific periods (e.g., monthly, quarterly, custom dates).
  • Sales Reports by Pharmacist: Evaluate individual pharmacist performance based on their sales contributions.
  • Year-wise Sales Summary: Gain a high-level overview of annual sales trends, crucial for long-term business planning and financial forecasting.

These reports empower administrators with the information needed to optimize inventory, refine marketing strategies, assess staff performance, and make informed business decisions that drive growth and profitability.

Profile Management: Personal Account Control

For administrators themselves, the system offers robust profile management capabilities, ensuring personal account security and up-to-date information. This includes the ability to:

  • Update Profile Details: Modify personal information such as name, contact details, and address.
  • Change Password: Securely update login credentials, enhancing account security.
  • Recover Password: A mechanism to regain access to the account in case of forgotten passwords, ensuring uninterrupted access to the system.

This feature provides administrators with autonomy over their personal system access and information, reinforcing security and convenience. The Admin Module, with its comprehensive suite of features, truly acts as the backbone of the Pharmacy Management System, providing the necessary tools for efficient oversight and strategic management of all pharmacy operations.

Pharmacist Module: Empowering Daily Operations

The Pharmacist Module is meticulously designed to empower pharmacists with the tools they need for efficient and accurate daily operations. This module focuses on streamlining patient interactions, managing sales, and providing quick access to critical information, allowing pharmacists to dedicate more time to patient care and less to administrative burdens.

Dashboard: Personalized Sales Overview

Upon logging into the system, each pharmacist is presented with a personalized dashboard tailored to their specific activities. Unlike the administrator's broader view, the pharmacist's dashboard provides immediate access to their individual sales performance, fostering a sense of ownership and enabling self-monitoring of targets. Key metrics typically displayed include:

  • Today's Sales: A real-time total of sales generated by the pharmacist on the current day.
  • Yesterday's Sales: A summary of the previous day's sales performance.
  • Last 7 Days Sales: An aggregated view of sales over the past week, helping pharmacists track their weekly progress and identify personal trends.

This personalized dashboard serves as a motivational tool and a quick reference for individual performance, allowing pharmacists to stay informed about their contributions to the pharmacy's overall success.

Inventory: Quick Stock Check

While administrators manage the overall inventory, pharmacists require quick and easy access to stock information during patient consultations or sales transactions. The Inventory feature in the Pharmacist Module provides a streamlined view of available medicine stock. This allows pharmacists to:

  • Check Available Stock: Instantly verify the quantity of any medicine in stock.
  • Confirm Availability: Quickly inform customers about medicine availability, preventing delays and improving service.

This functionality ensures that pharmacists can efficiently manage patient expectations and fulfill prescriptions without unnecessary interruptions, directly contributing to a smoother customer experience.

Search & Add to Cart: The Heart of Point of Sale (POS)

This is arguably the most critical feature for a pharmacist, forming the core of the Point of Sale (POS) system. It transforms the dispensing process into a fast, accurate, and user-friendly experience. The system enables pharmacists to:

  • Search for Medicine by Name: A powerful search function allows pharmacists to quickly find medicines using partial names or keywords, often with auto-completion for speed and accuracy.
  • Add Selected Medicines to the Cart: Once identified, medicines can be added to a digital shopping cart, specifying quantities and ensuring correct pricing.
  • Real-time Calculations: As items are added, the system automatically calculates subtotals, applies discounts, and determines the final amount due.
  • Customer Information Capture: Seamlessly add or select customer details for record-keeping and personalized service.
  • Invoice Generation: Upon completion of the transaction, the system generates a professional invoice, updates inventory levels, and records the sale, ensuring comprehensive transaction logging.

This integrated POS system significantly reduces manual errors, speeds up the checkout process, and provides a clear audit trail for every transaction, enhancing both efficiency and accountability.

Invoice Search: Accessing Transaction History

Similar to the Admin Module, pharmacists also need the ability to look up past invoices, particularly for customer inquiries or returns. The Invoice Search feature allows pharmacists to:

  • Search Invoices by Invoice Number: Quickly retrieve specific transaction records.
  • Search Invoices by Mobile Number: Efficiently find a customer's purchase history using their contact information.

This capability empowers pharmacists to provide excellent customer service by quickly resolving queries related to past purchases, offering reprints of invoices, or assisting with product returns.

Sales Report: Personal Performance Tracking

Beyond the dashboard's quick overview, the Sales Report feature allows pharmacists to delve deeper into their individual sales history. This provides a more detailed analysis of their performance over time. Pharmacists can:

  • View Sales History Filtered by Date: Generate reports for specific periods, allowing them to analyze their sales trends, identify peak performance times, or review their contributions over weeks or months.

This self-service reporting capability helps pharmacists understand their sales patterns, identify areas for improvement, and contribute more effectively to the pharmacy's business goals.

Profile Management: Personal Account Security

Just like administrators, pharmacists have access to profile management features to ensure their personal information is accurate and their account remains secure. This includes the ability to:

  • Update Profile Details: Modify personal information such as contact details or address.
  • Change Password: Securely update login credentials to maintain account security.
  • Recover Password: A mechanism to regain access to their account if they forget their password.

This feature ensures that pharmacists can maintain control over their personal system access and information, contributing to overall system security and user convenience. The Pharmacist Module, with its intuitive design and powerful features, transforms the daily tasks of dispensing and patient interaction into a streamlined, efficient, and secure process, ultimately enhancing productivity and patient satisfaction.

Conclusion: The Future of Pharmacy Management

In an increasingly digital world, the adoption of a robust Pharmacy Management System is no longer a luxury but a necessity for modern pharmacies. The system we've explored, built with the powerful combination of Node.js, Express.js, and MySQL, offers a comprehensive solution to the multifaceted challenges faced by pharmacy operations today. From meticulous inventory control and streamlined sales processes to insightful reporting and secure user management, this system empowers both administrators and pharmacists to operate with unparalleled efficiency and accuracy.

The Admin Module acts as the strategic nerve center, providing a bird's-eye view of the entire pharmacy ecosystem. Its intuitive dashboard delivers critical insights at a glance, while features like comprehensive medicine and company management, detailed sales reports, and robust pharmacist oversight ensure that every aspect of the business is meticulously controlled. This centralized control fosters better decision-making, optimizes resource allocation, and ultimately drives the pharmacy towards greater profitability and operational excellence.

Conversely, the Pharmacist Module is designed with the daily workflow of dispensing professionals in mind. Its user-friendly interface, particularly the advanced Point of Sale (POS) system, transforms routine tasks into seamless interactions. Features such as rapid medicine search, efficient cart management, and instant invoice generation significantly reduce transaction times and minimize errors, allowing pharmacists to dedicate more valuable time to patient counseling and care. The ability to quickly access inventory details and personal sales reports further enhances their productivity and empowers them to provide superior customer service.

Beyond the immediate operational benefits, a well-implemented PMS contributes significantly to regulatory compliance and data security. By centralizing data and automating record-keeping, it helps pharmacies adhere to stringent healthcare regulations, reducing the risk of penalties and enhancing patient trust. The secure, role-based authentication system ensures that sensitive patient and business data remains protected, a paramount concern in the healthcare sector.

In essence, a Pharmacy Management System powered by Node.js, Express.js, and MySQL is more than just a software solution; it's a strategic investment in the future of pharmacy. It enables pharmacies to adapt to evolving market demands, enhance patient satisfaction through improved service delivery, and achieve sustainable growth in a competitive landscape. By embracing such technological advancements, pharmacies can truly revolutionize their operations, moving towards a more efficient, secure, and patient-centric model of healthcare delivery. The journey to a smarter, more streamlined pharmacy begins with the right management system, paving the way for a healthier community and a more prosperous business.







Tuesday, 1 July 2025

Build Your Own Laundry Management System: A Free PHP Project with Source Code


Introduction: Revolutionizing Laundry Services with Technology


In today's fast-paced world, efficiency and convenience are paramount, especially in service industries. For laundry businesses, managing operations, tracking orders, and engaging with customers can be a complex task. This is where a robust Laundry Management System becomes indispensable. We are excited to introduce a comprehensive Free PHP Project designed to streamline every aspect of a laundry business, from customer requests to administrative oversight. This Free Educational Project offers a complete solution for students, developers, and entrepreneurs looking to understand and implement a real-world web application.

This article delves into the features, technology, and benefits of our PHP Project with Source code, providing you with everything you need to get started. Whether you're a student seeking a practical project for your portfolio or a business owner aiming to digitize your operations, this system is built to cater to your needs.

Build Your Own Laundry Management System: A Free PHP Project with Source Code






Key Features of Our Laundry Management System


Our Laundry Management System is packed with features designed to enhance both user experience and administrative efficiency. It is divided into two main modules:

User Module: Seamless Customer Experience


Customers are at the heart of any service business, and our system ensures they have a smooth and intuitive experience:

  • Easy Registration & Login: Users can quickly sign up and log in, with secure password handling.
  • Personalized Dashboard: A clean, modern dashboard provides an overview of their laundry requests, status, and quick access to services.
  • New Laundry Request: A user-friendly form allows customers to submit new laundry requests, specifying service types, weight, and pickup/delivery details. The system includes real-time price calculation for transparency.
  • Real-time Request Tracking: Customers can track the live status of their orders through an interactive timeline, from 'Pending' to 'Delivered'. This transparency significantly improves customer satisfaction.
  • Profile Management: Users can easily update their personal information and change their passwords securely.
  • Notifications: Automated notifications keep customers informed about their order status changes and other important updates.

Admin Module: Powerful Operational Control


For administrators, the system provides a robust set of tools to manage the entire laundry operation efficiently:

  • Comprehensive Dashboard: Get a bird's-eye view of key business metrics, including total users, pending requests, revenue, and recent activities.
  • User Management: Admins can view, manage, and monitor all registered users, including their contact details, order history, and account status.
  • Laundry Request Management: A centralized system to process, update, and track all customer requests. Admins can change order statuses, add notes, and ensure smooth workflow.
  • Pricing Management: Easily configure and update laundry service types and their corresponding prices. This dynamic pricing system allows for flexibility and quick adjustments based on market needs.
  • Detailed Reports & Analytics: Generate insightful reports on various aspects of the business, such as monthly trends, customer spending habits, and service popularity. These reports are crucial for data-driven decision-making.
  • Admin Notifications: Receive alerts for new requests, cancellations, and other critical system events.

This rich feature set makes our Laundry Management System a complete solution for modern laundry businesses.

Technology Stack: Modern, Robust, and Scalable


Our Laundry Management System is built using a modern and widely adopted technology stack, ensuring its robustness, scalability, and ease of maintenance:

  • Backend: Developed with PHP 8, leveraging its latest features for improved performance, security, and developer experience. PHP 8 provides a solid foundation for handling business logic and server-side operations.
  • Database: Utilizes MySQL, a powerful and reliable open-source relational database management system. The database schema is meticulously designed to efficiently store and retrieve all operational data, from user profiles to laundry requests and pricing.
  • Frontend: Features a sleek and responsive user interface built with Bootstrap 5, HTML5, CSS3, and JavaScript. Bootstrap 5 ensures that the system looks great and functions flawlessly across all devices, from desktops to mobile phones, providing an excellent user experience.
  • Security: Implements best practices for web security, including password hashing, prepared statements to prevent SQL injection, input sanitization, and CSRF protection.

This combination of technologies makes the Laundry Management System a high-performance and secure application, ready for real-world deployment.

Why Choose This Free PHP Project?


This Free PHP Project stands out for several reasons, making it an invaluable resource:

  1. Comprehensive Functionality: It covers all essential aspects of laundry management, providing a complete solution out-of-the-box.
  2. Educational Value: As a Free Educational Project, it serves as an excellent learning tool for students and aspiring web developers. The well-structured code and clear architecture make it easy to understand and modify.
  3. Real-world Application: This isn't just a theoretical exercise; it's a practical system that can be adapted for actual use in a laundry business.
  4. PHP Project with Source Code: You get full access to the entire source code, allowing for deep customization, integration with other systems, and further development. This transparency is crucial for learning and adapting the project to specific needs.
  5. SEO Friendly: The project is designed with SEO best practices in mind, making it easier for businesses to attract customers online.
  6. Cost-Effective: Being a Free PHP Project, it eliminates initial software licensing costs, making it accessible to a wider audience.

Whether you're looking to enhance your coding skills, build a portfolio, or find a ready-to-use solution for a laundry business, this project offers immense value.

Getting Started with Your Free PHP Project


Ready to dive into your own Laundry Management System? Getting started is straightforward:

  1. Download the Source Code: Access the complete PHP Project with Source code from our repository.
  2. Set Up Your Environment: Ensure you have PHP 8 and MySQL installed on your web server.
  3. Database Import: Import the provided lms_database.sql file into your MySQL database to set up the necessary tables.
  4. Configuration: Update the database connection details in the config/database.php file.
  5. Run the Installation Script: Navigate to install.php in your browser to complete the setup, including creating an admin user and populating default pricing.

Detailed installation instructions and system requirements are available in the README.md file included with the source code. This Free Educational Project is designed for easy deployment and customization.

Conclusion: Empowering Laundry Businesses and Developers


Our PHP Project on Laundry Management System using MySQL offers a powerful, efficient, and user-friendly solution for modern laundry businesses. With its comprehensive features, robust technology stack, and intuitive design, it stands as a testament to what can be achieved with open-source tools.

Whether you are a student looking for a challenging Free Educational Project, a developer seeking a solid foundation for a custom solution, or a business owner ready to embrace digital transformation, this Free PHP Project provides the perfect starting point. Download the PHP Project with Source code today and take the first step towards a more organized and profitable laundry operation!







Sunday, 29 June 2025

How to Reduce PDF Size: Practical Methods That Work

How to Reduce PDF Size: Practical Methods That Work

PDF files are everywhere — in business reports, academic papers, e-books, brochures, and more. But large PDF files can be a headache. They take up storage space, slow down sharing, and may exceed upload limits for email or web forms. The good news? Reducing a PDF’s size is easy once you know how. This guide walks you through effective methods, tools, and tips to shrink your PDF files without sacrificing essential quality.

Why Reduce PDF Size?


Before we dive into how, let’s quickly cover why it matters:

  • Faster sharing — Smaller files upload, download, and send faster.
  • Less storage use — Saves space on your device or cloud service.
  • Better compatibility — Many platforms have file size limits for uploads.
  • Improved user experience — Readers won’t wait forever for a file to open.

1. Use “Save As” or “Save As Optimized”


Often, the simplest way to reduce a PDF’s size is to resave it:

  • Adobe Acrobat Pro: Go to File → Save As Other → Reduced Size PDF.
  • Preview on macOS: Open your PDF → File → Export → Choose Quartz Filter → Select Reduce File Size.

2. Compress Images in the PDF


Images often make up the bulk of a PDF’s size. You can:

  • Lower image resolution: Convert high-resolution images to 150 dpi or 72 dpi.
  • Change image format: Use JPEG instead of PNG or TIFF.
  • Remove unnecessary images.

3. Remove Embedded Fonts


Embedded fonts increase file size. To reduce this:

  • Use standard fonts like Arial or Helvetica.
  • Subset fonts so only used characters are embedded.

4. Flatten Layers and Forms


Flattening layers reduces size and increases compatibility:

  • In Acrobat Pro: Print Production → Flattener Preview.
  • Or print to PDF using “Microsoft Print to PDF”.

5. Remove Unused Elements


Clean up the file by removing:

  • Metadata (author, title, keywords)
  • Hidden layers or annotations
  • Attachments
  • Bookmarks or thumbnails




6. Use Online Compression Tools


If you don’t have premium software, try free online tools:

  • PDFsail
  • ILovePDF
  • PDFCompressor
  • Adobe Acrobat Online

Note: Always review privacy policies before uploading sensitive files.

7. Split Large PDFs


Break your PDF into smaller files:

  • Use Acrobat, Preview, or online split tools.
  • Divide by pages, chapters, or sections.

8. Convert to Other Formats and Back


Convert the PDF to Word or PowerPoint, clean it up, and export it back to PDF for smaller size.

9. Use Command-Line Tools


For advanced users, Ghostscript can be used:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen \
-dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf
  

PDFSETTINGS options:

  • /screen (lowest quality, smallest size)
  • /ebook (medium quality)
  • /printer (high quality)
  • /prepress (best quality, largest file)

10. Adjust Export Settings When Creating PDFs


  • In Word or PowerPoint, choose “Minimum size” or “Web” PDF option.
  • In design apps, reduce image resolution and flatten layers.
  • Avoid embedding fonts unless necessary.

Compression Trade-Offs


Compression often trades quality for size:

  • Text-heavy PDFs: Can often shrink without visible loss.
  • Image-heavy PDFs: May lose quality when compressed.
  • Interactive PDFs: May lose functionality when flattened.

Final Tips


  • Test different methods and combinations.
  • Keep a backup of the original file.
  • Use batch tools for repetitive tasks.

Summary


Shrinking PDF size doesn’t have to be difficult. Whether using built-in software features, online tools, or advanced tools like Ghostscript, there’s a solution that fits your needs. With these methods, you can make your PDFs easier to share, store, and manage — without unnecessary bloat.

Monday, 17 March 2025

Real-time Notification System in PHP using Ratchet WebSocket


In modern web applications, real-time notifications are essential for enhancing user experience. Whether it's for chat applications, order updates, or user interactions, instant notifications keep users engaged. In this tutorial, we will build a real-time notification system in PHP using Ratchet WebSocket.

Why Use WebSockets for Real-Time Notifications?


Traditional polling methods with AJAX requests put a load on the server by continuously checking for updates. WebSockets, on the other hand, enable a persistent connection between the client and the server, allowing instant two-way communication.

Features of Our Notification System:


  • Users receive real-time notifications without refreshing the page.
  • Unread notification count updates dynamically.
  • Notifications appear in a dropdown menu.
  • Clicking a notification marks it as read instantly.

Uses of Real-Time Notification System


Real-time notifications can be used in various applications, including:

  • E-commerce platforms: Alert users about order status updates, flash sales, and price drops.
  • Social media networks: Notify users about likes, comments, shares, and friend requests.
  • Banking and finance apps: Inform users about transactions, payment reminders, and security alerts.
  • Healthcare systems: Notify doctors and patients about appointment confirmations, medical reports, and prescription updates.
  • Customer support systems: Provide instant responses, ticket updates, and live chat notifications.
  • Project management tools: Alert team members about task assignments, deadlines, and project updates.

Benefits of a Real-Time Notification System


  • Improved user engagement: Keeps users informed and active on the platform.
  • Faster response times: Enables instant communication and quick decision-making.
  • Better user experience: Eliminates the need for page refreshes, providing seamless interaction.
  • Efficient server resource utilization: Reduces server load compared to traditional polling methods.
  • Enhanced security: Immediate alerts for login attempts, unauthorized access, and account changes.

Examples of Real-Time Notification Systems


  • Facebook, Twitter, Instagram: Social media notifications for likes, comments, and mentions.
  • WhatsApp, Slack, Microsoft Teams: Instant messaging and chat notifications.
  • Amazon, Flipkart, eBay: Order updates, shipment tracking, and product promotions.
  • Gmail, Outlook, Yahoo Mail: Email notifications for new messages.
  • Trello, Asana, Jira: Task management and project update notifications.




Setting Up Ratchet WebSocket in PHP


Step 1: Install Ratchet WebSocket Library


First, install Ratchet using Composer:

	
		composer require cboden/ratchet
	

Step 2: Create the WebSocket Server (server.php)


Create a server.php file to handle WebSocket connections and notifications.

	
		<?php

			require 'vendor/autoload.php';

			use Ratchet\Http\HttpServer;
			use Ratchet\Server\IoServer;
			use Ratchet\WebSocket\WsServer;
			use Ratchet\MessageComponentInterface;
			use Ratchet\ConnectionInterface;

			class NotificationServer implements MessageComponentInterface {

				protected $clients;
				private $pdo;

				public function __construct(){
					$this->clients = new \SplObjectStorage;

					$this->pdo = new PDO("mysql:host=localhost;dbname=testing", "root", "1234567890");

				}

				public function onOpen(ConnectionInterface $conn){
					$this->clients->attach($conn);
					echo "New connection! - ({$conn->resourceId})\n";
					$this->sendNotifications($conn);
				}

				public function onMessage(ConnectionInterface $from, $msg){
					$data = json_decode($msg, true);

					if(isset($data['type']) && $data['type'] === 'new_comment'){
						$statement = $this->pdo->prepare("INSERT INTO comments (comment_subject, comment_text, comment_status) VALUES (?, ?, 0)");
						$statement->execute([$data['subject'], $data['comment']]);
						$this->broadcastNotifications();
					}

					if(isset($data['type']) && $data['type'] === 'mark_as_read'){
						$this->markNotificationAsRead($data['comment_id']);
						$this->broadcastNotifications(); // Refresh for all users
					}
				}

				public function onClose(ConnectionInterface $conn){
					$this->clients->detach($conn);
					echo "Connection {$conn->resourceId} has disconnected\n";
				}

				public function onError(ConnectionInterface $conn, \Exception $e){
					echo "An error occurred: {$e->getMessage()}\n";
					$conn->close();
				}

				private function broadcastNotifications()
				{
					foreach($this->clients as $client){
						$this->sendNotifications($client);
					}
				}

				private function markNotificationAsRead($commentId){
					$statement = $this->pdo->prepare("UPDATE comments SET comment_status = 1 WHERE comment_id = ?");
					$statement->execute([$commentId]);
				}

				private function sendNotifications(ConnectionInterface $conn){
					$statement = $this->pdo->query("SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5");

					$notifications = $statement->fetchAll(PDO::FETCH_ASSOC);

					$statement = $this->pdo->query("SELECT COUNT(*) AS unread_count FROM comments WHERE comment_status = 0");

					$unreadCount = $statement->fetch(PDO::FETCH_ASSOC)["unread_count"];

					$response = [
						'type' => 'notification',
						'notifications' => $notifications,
						'unread_count'	=>	$unreadCount
					];

					$conn->send(json_encode($response));
				}
			}

			// Start the WebSocket server

			$server = IoServer::factory(
				new HttpServer(
					new WsServer(
						new NotificationServer()
					)
				),
				8080
			);

			echo "WebSocket server started on port 8080\n";
			$server->run();

			?>
	

Step 3: Send Comment (add_comment.php)


Now for Subject Comment data to Websocket server, we have to create add_comment.php file and under this file, We have to write following HTML and JavaScript code for submit comment form data to Ratchet Websocket server.

add_comment.php
	
		<!DOCTYPE html>
			<html>
			<head>
				<title>Add Comment</title>
				<meta charset="utf-8">
				<meta name="viewport" content="width=device-width, initial-scale=1">
				<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
			</head>
			<body class="container mt-5">
				<h2 class="text-center mb-4">Add a Comment</h2>
				<div class="card shadow-sm p-4">
					<form id="commentForm" onsubmit="event.preventDefault(); sendComment(); ">
						<div class="mb-3">
							<label class="form-label">Enter Subject</label>
							<input type="text" class="form-control" id="subject" required />
						</div>
						<div class="mb-3">
							<label class="form-label">Enter Comment</label>
							<textarea class="form-control" id="comment" rows="3" required></textarea>
						</div>
						<button type="submit" class="btn btn-primary w-100">Post Comment</button>
					</form>
				</div>
				<script>

					var ws = new WebSocket("ws://localhost:8080");

					function sendComment()
					{
						var subject = document.getElementById('subject').value;
						var comment = document.getElementById('comment').value;

						if(subject && comment){
							var data = {
								type : "new_comment",
								subject : subject,
								comment : comment
							};

							ws.send(JSON.stringify(data));

							document.getElementById("commentForm").reset();

							alert("Comment Added!");

						} else {
							alert("Both fields are required!");
						}
					}

				</script>
			</body>
			</html>
	

Step 4 : Create MySQL Table


This is dynamic Real-Time Notification System using Ratchet Websocket, So for store notification data we have to create Comments table in our MySQL database. So for this We have to run following SQL script for create comments table in MySQL database.

	
		CREATE TABLE `comments` (
		  `comment_id` int NOT NULL AUTO_INCREMENT,
		  `comment_subject` varchar(250) NOT NULL,
		  `comment_text` text NOT NULL,
		  `comment_status` int NOT NULL DEFAULT '0',
		  PRIMARY KEY (`comment_id`)
		) ENGINE=InnoDB;
	

Step 5 : Display Notification


For Display Real-time notification to connected user, we have to create notifications.php file. Under this file, we have to write HTML & JavaScript code for display Real-time notification data on web page to connected user.

notifications.php
	
		<!DOCTYPE html>
			<html lang="en">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width, initial-scale=1">
				<title>Real-Time Notifications</title>
				<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
			</head>
			<body class="container mt-5">
				<h2 class="text-center mb-4">Real-Time Notifications</h2>
				<div class="card shadow-sm p-4">
					<div class="text-end">
						<div class="dropdown">
							<button class="btn btn-primary dropdown-toggle" type="button" id="notificationDropdown" data-bs-toggle="dropdown" aria-expanded="false">
								Notifications <span id="unreadCount" class="badge bg-danger">0</span>
							</button>
							<ul class="dropdown-menu dropdown-menu-end" id="notificationList">
								<li><a class="dropdown-item text-center">No new notifications</a></li>
							</ul>
						</div>
					</div>
				</div>
				<script>
					var conn = new WebSocket('ws://localhost:8080');

					conn.onopen = function(){
						console.log('WebSocket Connected!');
					};

					conn.onmessage = function(event){
						var data = JSON.parse(event.data);
						if(data.type === 'notification'){
							updateNotificationDropdown(data.notifications);
						}
					};

					function updateNotificationDropdown(notifications){
						var notificationList = document.getElementById('notificationList');
						var unreadBadge = document.getElementById('unreadCount');

						notificationList.innerHTML = '';

						if(notifications.length === 0){
							notificationList.innerHTML = `<li><a class="dropdown-item text-center">No new notifications</a></li>`;
							unreadBadge.style.display = 'none';
							return;
						}

						let count = 0;

						notifications.forEach(function(notification){

							let li = document.createElement('li');
							let a = document.createElement('a');

							a.className = 'dropdown-item';

							a.href = '#';

							a.innerHTML = `<strong>${notification.comment_subject}</strong>:${notification.comment_text}`;

							if(notification.comment_status == 0){
								console.log('test');
								a.style.fontWeight = 'bold';
								count++;
							}

							// Mark as read on click
							a.onclick = function(){
								markAsRead(notification.comment_id);
							};

							li.appendChild(a);
							notificationList.appendChild(li);
						});

						unreadBadge.textContent = count;
						unreadBadge.style.display = count > 0 ? "inline" : "none";
					}

					function markAsRead(commentId){
						conn.send(JSON.stringify({ type : "mark_as_read", comment_id : commentId }));
					}

				</script>
			</body>
			</html>
			<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
	

Run the WebSocket server using:

	
		php server.php
	

Output


In below Screenshot you can find the output of this Real-time Notification system application.


Real-time Notification System in PHP using Ratchet WebSocket


Download Source Code


If you want to download complete source code of PHP MySQL Real-time Notification System using Ratchet Websocket, then below you can find source code download link.





Tuesday, 28 January 2025

Employee Leave Management System in PHP using MySQL

Employee Leave Management System in PHP using MySQL


Introduction


An Employee Leave Management System is a powerful tool that simplifies the leave application and management process within an organization. It eliminates the need for manual tracking, paperwork, and inefficiencies by providing a digital platform for employees to apply for leave and administrators to manage requests seamlessly. This system ensures transparency, reduces administrative overhead, and improves the overall experience for both employees and management.





Features of the Employee Leave Management System


  1. Admin Dashboard: Provides an overview of total employees, departments, leave types, and leave statistics such as pending, approved, and rejected leave applications.
  2. Department Management: Add, edit, and manage departments with active/inactive status.
  3. Employee Management: Add, update, and manage employee details, including activation or deactivation of employee accounts.
  4. Leave Type Management: Define leave types such as casual leave, sick leave, and maternity leave with configurable allowances.
  5. Leave Application Processing: Admins can view, approve, reject, and add remarks to employee leave applications.
  6. Employee Dashboard: Allows employees to track their leave balance, view leave history, and stay updated on the status of their applications.
  7. Notifications: Real-time updates for leave application status changes and important announcements.
  8. Leave Balance Management: Tracks leave entitlements and deductions for each employee.
  9. Secure Login System: Role-based access for admins and employees with password encryption.
  10. Responsive Design: Fully optimized for use on desktops, tablets, and mobile devices.



Technologies Used


This Employee Leave Management System is built using the following web technologies:

  • Backend: PHP 8 for server-side scripting and MySQL for database management.
  • Frontend: HTML, CSS, and JavaScript for creating a responsive and user-friendly interface.
  • Frameworks/Libraries:
    • Bootstrap 5 for responsive design and styling.
    • jQuery for dynamic interactions and AJAX functionality.
    • CKEditor for rich text editing in leave descriptions.
  • Security: Password encryption using PHP's password hashing functions and secure session management.



Why Use This System?


  • Efficiency: Automates the entire leave management process, reducing manual errors and saving time.
  • Transparency: Employees can track their leave status in real-time, fostering trust and accountability.
  • Customization: Flexible leave types, allowances, and status updates to suit any organization's policies.
  • Cost-Effective: Minimizes administrative costs associated with traditional leave management methods.
  • Data Security: Ensures sensitive employee and leave data is securely stored and accessed.



Benefits of the System


  1. Simplified Leave Application: Employees can easily apply for leave without the need for paperwork or manual follow-ups.
  2. Better Decision-Making: Administrators have access to leave statistics and employee availability, making resource planning easier.
  3. Improved Productivity: With streamlined processes, both employees and administrators can focus on their core responsibilities.
  4. Scalability: The system can grow with the organization, accommodating more employees and leave types as needed.
  5. Compliance: Helps organizations adhere to labor laws by maintaining accurate leave records.





Database Structure


Below is a simplified structure of the database used in the Employee Leave Management System:

  • elms_admin:
    • admin_id (Primary Key)
    • admin_user_name
    • admin_password
  • elms_department:
    • department_id (Primary Key)
    • department_name
    • added_on
    • updated_on
  • elms_leave_type:
    • leave_type_id (Primary Key)
    • leave_type_name
    • added_on
    • updated_on
  • elms_employee:
    • employee_id (Primary Key)
    • employee_unique_code
    • employee_first_name
    • employee_last_name
    • employee_email
    • employee_password
    • employee_gender
    • employee_birthdate
    • employee_department (Foreign Key)
    • employee_address
    • employee_city
    • employee_country
    • employee_mobile_number
    • employee_status
  • elms_leave:
    • leave_id (Primary Key)
    • employee_id (Foreign Key)
    • leave_type (Foreign Key)
    • leave_start_date
    • leave_end_date
    • leave_description
    • leave_admin_remark
    • leave_status (Pending, Admin Read, Approved, Rejected)
    • leave_apply_date
    • leave_admin_remark_date



Download the Source Code


You can download the complete source code of this Employee Leave Management System from the link below:




Conclusion


The Employee Leave Management System is a practical and efficient solution for organizations of all sizes. It simplifies leave management, ensures transparency, and saves time for both employees and administrators. By implementing this system, organizations can enhance productivity, ensure compliance, and create a better work environment. Start using the Employee Leave Management System today and take a step towards modernizing your workforce management!