0% found this document useful (0 votes)
5 views80 pages

Final Project File

Uploaded by

rvasu8504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views80 pages

Final Project File

Uploaded by

rvasu8504
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

BOOK BANK

ExNo:1a
Date: IDENTIFY A SOFTWARE SYSTEM THAT NEEDS TO BE DEVELOPED

AIM :
To identify a software system that needs to be developed.

Book Bank:
A Book Bank is an initiative by colleges aimed at assisting financially underprivileged and
academically strong students by providing textbooks at a subsidized rate. Instead of borrowing and
returning books, this updated system allows students to purchase textbooks at 75% of their actual cost,
making ownership affordable and accessible.

Students must register on the platform, either as new users or by logging in as returning members.
After registration, students can select their academic year to view a customized list of textbooks
relevant to their course curriculum. They can then choose the books they require and submit a
purchase request to the administrator for verification.

The primary aim is to empower students from economically weaker backgrounds by helping them
own important academic resources without facing high financial pressure. This model of book
purchase ensures long-term use of textbooks and eliminates the complexities of returning them at the
end of the session.

To access this service, students are required to pay 75% of the total book cost at the college office.
After payment, they must present the receipt to the Book Bank clerk to receive their books. The books
are then considered the property of the student and need not be returned.

Students are responsible for checking the condition of the books before issuance. Any pre-existing
damage must be reported immediately. Once issued, the books belong to the student and are not
eligible for return or refund. The Book Bank strictly deals with textbooks only, and does not provide
supplementary materials such as guides, notes, or solved papers.

Process Flow

Student Registration
o New Students: Register by providing personal details.
o Existing Students: Log in using the “old member” option.

Academic Year Selection


o Upon login or registration, students select their academic year (1st, 2nd, 3rd, or 4th year) to
view relevant textbooks.

Book Selection & Request Submission


o Students browse the available textbook list and select the required ones.
o The request is then submitted to the administrator for verification.
Administrator Verification

o The administrator checks the availability of the requested books and confirms whether the
student is eligible.
o The approval or denial of the request is based on the book’s availability and the eligibility criteria.

Book Issuance
o If approved, the student must deposit 75% of the book’s price at the college office and present
the receipt to the book bank clerk.
o Once these steps are completed, the books are considered purchased and issued to the student.

Book Purchase & Accountability


o Ownership: Books issued are permanently owned by the student.
o No Returns: There is no requirement to return books after exams.
o Condition of Books: Any damage must be reported before books are issued.
o Responsibility: Students are expected to handle the books with care and understand that
no replacements or refunds are provided once books are issued.
RESULT

Thus a software system that needs to be developed was identified successfully.


ExNo:2
Date: CREATION OF SOFTWARE REQUIREMENT SPECIFICATION

AIM :
To document the Software Requirements Specification (SRS) for the Book Bank Management
System. The objective of this SRS is to define and outline a software solution that automates the
operations of a college Book Bank. The system aims to assist financially disadvantaged and
academically deserving students by issuing textbooks at a subsidized deposit. This digital solution
will simplify and streamline student registration, book allocation, inventory tracking, return handling,
and administrative control with improved efficiency and transparency.

SRS (Software Requirement Specifications) Document


A Software Requirements Specification (SRS) is a detailed and structured description of a
software system's intended behavior. This includes both functional and non-functional aspects of
the system. Functional requirements describe the system’s core operations, like user interactions
and data processing, while non-functional requirements set performance benchmarks such as
speed, security, and usability. The SRS acts as a mutual agreement between the stakeholders and
the developers, ensuring a clear understanding of what the system is expected to achieve.
 Functionality: Includes secure student login, book catalog browsing, request submissions, and
admin-level management of book status, deposits, and return tracking.
 Non-Functional Requirements: Emphasize system responsiveness, data security, scalability,
user-friendliness, and reliability during peak usage.

The purpose of the SRS is to:

1. Establish the basis for agreement between the stakeholders and developers on the system’s
expected behavior.
2. Provide clear documentation for software design and development.
3. Reduce misunderstandings and streamline development time.
4. Enable better cost and schedule estimations.
5. Serve as a foundation for future validation and verification.
6. Ensure easy system transfer and knowledge sharing.
7. Facilitate enhancements and maintenance of the system.
Problem Statement:
The Book Bank aims to support underprivileged but deserving students by lending them required
academic textbooks at a minimal refundable deposit. Currently, the process is manual and inefficient,
prone to delays, errors, and lack of proper record-keeping. Students must submit 75% of the book's price
at the college office and present a receipt to borrow books. The books must be returned in good
condition after exams, or else penalties apply. The manual nature of issuing and tracking books leads to
inconsistencies and loss of accountability. A web-based, automated system is needed to manage student
requests, eligibility verification, deposit tracking, and book returns in an efficient, transparent, and
accountable manner.

Requirement Analysis :

The goal of the requirement analysis is to understand and translate organizational needs into a formal set
of functional and technical software requirements. This helps build the foundation for system design,
testing, and maintenance.

Key considerations include:

 Managing secure user registrations and logins

 Academic-year-based book categorization and display

 Book request flow and eligibility validation

 Managing book issue, return, penalties, and deposits

 Role-based interfaces for students and administrators

 Real-time tracking and inventory management

Modules of Book Bank :

1. User Registration and Login


o Enables secure student account creation and login.
o Handles credential encryption and validation.
2. Academic Year Selection
o Allows students to filter books based on their current academic year.
3. Book Management
o Admin can add, update, or remove book records.
o Displays book availability and metadata (title, author, etc.).
4. Book Request and Approval
o Students submit book requests.
o Admin approves/rejects requests based on eligibility and inventory.
5. Book Issuance
o System handles issuing books and generates receipt data.
o Stores deposit and due date records.
6. Book Return and Accountability
o Students return books and report any existing damage.
o Admin evaluates condition and applies penalties if needed.
7. Admin Dashboard
o Overview of total inventory, issued books, pending requests.
o Provides full control over user and book records.
 Inventory Tracking
o Real-time tracking of book statuses: Available, Issued, Returned.
o Supports planning and reporting for future academic sessions.

Hardware Requirements Book Bank :


 Processor: Intel Pentium IV or equivalent
 Processor Speed: Minimum 1 GHz
 RAM: Minimum 512 MB
 Hard Disk: Minimum 40 GB free storage

software Requirements of Book Bank:


 Operating System: Windows 10/11, Linux (Ubuntu), or macOS
 Development Tools: Visual Studio Code, Git, Postman
 Frontend: React.js (HTML, CSS, JavaScript)
 Backend: Node.js with Express.js
 Database: MongoDB (Cloud or local setup via MongoDB Compass)
 Authentication: JSON Web Tokens (JWT)
 Server: Node-based server with RESTful API architecture
 Browsers: Chrome, Firefox, Edge

Functional Requirement of Book Bank

User Registration & Login


 Students register using their name, roll number, department, and password.
 Secure authentication using hashed passwords and JWT-based session control.
Book Selection
 Users browse a filtered list of textbooks based on academic year.
 Each book shows title, author, and status (Available/Issued).
Book Request Submission
 Students can request books; the system logs these as pending.
 Prevents multiple requests for the same title per user.
Admin Verification & Approval
 Admins validate request eligibility and stock.
 Requests are approved or rejected; book status is updated accordingly.
Book Issuance Tracking
 Once approved, books are marked as “Issued” and cannot be requested again.
 Due dates are recorded, and deposit status is tracked.
Database Management
 The MongoDB database stores collections like Users, Books, Requests, Returns.
 Ensures data consistency and supports easy retrieval.
Book Return Feature
 Students can initiate a return request.
 Admin inspects the book and confirms status.
Non-Functional Requirement of Recruitment System:

Performance
 System should respond to user interactions in under 1 second.
 Optimized API calls and database queries for fast processing.

Scalability
 Designed to handle growing user and data volumes.
Efficient use of cloud services and modular code for
scaling.

Security
 All sensitive data encrypted and access-controlled.
 Implements role-based authentication and secure API endpoints.

Usability
 Clean, mobile-friendly interface with intuitive
navigation. User guidance provided via tooltips and
form validation.

Reliability
 Ensures stable behavior under all expected loads.
 Includes error recovery, transaction logs, and retry mechanisms.

Maintainability
 Code organized using MVC pattern and reusable components.
Easy to debug and extend for future updates.

Portability

 Compatible with all major platforms due to use of Node.js and


React. Easily deployable on services like Heroku, Vercel, or
Render.
Conclusion

The Book Bank Management System is a purpose-driven platform that aims to reduce the academic burden on
underprivileged students by ensuring access to essential textbooks. By leveraging a modern web-based architecture, it
streamlines the entire workflow from registration to returns. It also promotes transparency, reduces manual errors, and
provides a reliable infrastructure for administrators. In essence, this system helps achieve equitable access to education
by combining thoughtful policy with efficient technology.
UNIFIED MODELING LANGUAGE
DESIGN
Design has a great impact on the overall success of software development projects. A
large payoff is associated with creating a good design up from before writing a single code, while
this is due to all programming classes and objects understanding approach better design usually
simplifies the implementation and maintenance. During the design phase we must evaluate the
model to actual objects that can be perform the required tasks. There is a shift in emphasis from
the application domain to implementation. The class during analysis provides as a framework for
design phases.
MODELING
Building a model for a software system prior to its construction is as essential as having
a blueprint for building a large building. Good models are essential for communication among
project teams. A modeling language must include
• Model elements-fundamental modeling concepts and semantics. Notation- visual
rendering of model elements.
• Guidelines-expression of usage within the trade
The use of visual notation to represent or model a problem can provide us with several benefits
relating to clarity, familiarity, maintenance, and simplification.
UNIFIED MODELING LANGUAGE
The Unified Modeling Language (UML) is a language for specifying, visualizing,
constructing, and documenting the artifacts of software systems and their components. UML is a
graphical language with sets of rules and semantics. The rules and semantics of a model are
expressed in English, in a form known as object constraint language (OCL). OCL is a
specification language that uses simple logic for specifying the properties of a system. The UML
is not intended to be a visual programming language in the sense of having all the necessary
visual and semantic support to replace programming languages.
UML DIAGRAMS
UML defines nine graphical diagrams

 Use-case diagram
 Class diagram
 Behavior Diagram
 Interaction Diagram
 Sequence Diagram
 Collaboration diagram
 State chart diagram
 Activity diagram
 Implementation diagram
 Component diagram
ExNo:3
Date: USE CASE DIAGRAM

AIM :
To identify Use Cases and develop the Use Case model for the identified requirements.

USE CASE DIAGRAM


A use-case diagram is a graph of actors, a set of use cases enclosed by a system boundary,
communication (participation) associations between the actors and the use cases, and
generalization among the use cases. It shows the relationship among the actors and use cases
within a system . They separate the system into actors and use cases. An actor represents the
roles that can be played by the user of the system.

Use case describes the behavior of the system.


 1. Use cases. A use case describes a sequence of actions that provide something of measurable
value to an actor and is drawn as a horizontal ellipse.
 2. Actors. An actor is a person, organization, or external system that plays a role in one or
more interactions with your system. The actors are drawn as stick figures.
 3. Associations. Associations between actors and use cases are indicated in use case diagrams
by solid lines. An association exists whenever an actor is involved with an inter action
described by a use case.
 4. System boundary boxes (optional). A rectangle around the use cases is called the system
boundary box and is used to indicate the scope of the system.
 5. Packages (optional). Packages are UML constructs that enable you to organize model
elements (such as use cases) into groups.

RELATIONSHIPS IN USE CASE DIAGRAM


Three relationships are supported among use cases by the UML standard, which describes
graphical notation for these relationships.
1. Include(<<include>>)
i. A given use case may include another. The first use case often depends on the outcome of the
included use case. This is useful for extracting truly common behaviors from multiple use cases
into a single description.
2. Extend(<<extend>>)
i. A given use case, (the extension) may extend another. This relationship indicates that the behavior
of the extension use case may be inserted in the extended use case under some conditions. This
can be useful for dealing with special cases, or in accommodating new requirements during
system maintenance and extension.
3. Generalization
i. A generalization/ specialization relationship exists among use cases. A given use case may be a
specialized form of an existing use case. The notation is a solid line ending in a hollow triangle
drawn from the specialized to the more general use case. This resembles the object-oriented
concept of sub-classing, in practice it can be both useful and effective to factor common
behaviors, constraints and assumptions to the general use case, describe them once, and deal
same as except details in the specialized cases.
PROCEDURE
1. Identify distinct actors and use cases.

2. The external actors are placed to the left of the use case and the internal actors to the right.
3. Select Model | Add Diagram | Use Case Diagram in Menu Bar or select Add Diagram | Use
Case Diagram in Context Menu in Star UML.
4. Name the diagram and draw the diagram using the symbols present in the Star UML toolbox
according to the identified actors and use cases.
5. Draw the relationship between the use cases and actors as extend, include and generalization
types using the symbols.

USE CASE DIAGRAM FOR AUTHENTICATION


USE CASE DIAGRAM FOR BOOK MANAGEMENT
USECASE DIAGRAM FOR PURCHASE BOOK
RESULT:
Thus, the use case diagram was drawn successfully using Star UML for the identified requirements.
ExNo:4
Date: UML-CLASS DIAGRAM

AIM :
To identify conceptual classes and develop a domain model with UML Class diagram

CLASS DIAGRAM :
In the Unified Modeling Language (UML), a class diagram is a collection of static modeling
elements, such as classes and their relationships, connected as a graph to each other and to their
contents; their internal structures, and their relationships to other classes.
A class is drawn as a rectangle with three components separated by horizontal lines. The top
compartment holds the class name, other general properties of the class, such as attributes, are in
the middle compartment, and the bottom compartment holds a list of operations. Either or both
the attribute and operation compartments may be suppressed.
A separator line is not drawn for a missing compartment if a compartment is suppressed; no
inference can be drawn about the presence or absence of elements in it. The class name and other
properties should be displayed in up to three sections. A stylistic convention of UML is to use an
italic font for abstract classes and a normal (roman) font for concrete classes.

PROCEDURE
1. Identify the classes that are taking part in the diagram.

2. Select Model | Add Diagram | Class Diagram in the Menu Bar or select Add Diagram |
Class Diagram in Context Menu.
3. Select class diagram, specify the attributes, operations or methods, parameters, datatype by
selecting following.
• Select Model | Add | Class in Menu Bar or Add | Class in Context Menu.
• Select Model | Add | Attribute in Menu Bar or Add | Attribute in Context Menu.
• Select Model | Add | Operation in Menu Bar or Add | Operation in Context Menu.
• Select Model | Add | Parameter in Menu Bar or Add | Parameter in Context Menu.
Select Model | Add | DataTypein Menu Bar or Add | Datatype in Context Menu.
4. Create the class diagram for the project.

5. Explicitly denote the relation between classes by generalizations, associations, multiplicities


and cardinalities.
6. Save the file.
CLASS DIAGRAM FOR BOOKBANK
RESULT
Thus, the class diagram was drawn successfully using StarUML for the identified
requirements.
ExNo:5
Date: UML- SEQUENCE AND COLLABORATION DIAGRAMS

AIM :
To draw sequence and collaboration diagrams for the identified scenarios and the
interaction between objects.

INTERACTION DIAGRAM :
Sequence diagram describes the behavior of the system by viewing the interaction
between the system and its environment. It represents the class at the top and their lifetime, their
interactions as relations.
A collaboration diagram, also called a communication diagram or interaction diagram, is
an illustration of the relationships and interactions among software objects in the Unified
Modeling Language (UML).
SEQUENCE DIAGRAM

PROCEDURE
1. Identify the initiator of the process.

2. Associate each actor with a class whether it uses or provides services. 3. Each actor is
represented as a rectangle.
4. The sequence of flow is denoted by the name of the operations to be done.
5. The actors are separated by vertical dashed lines and sequence flow is indicated through arrows.
6. Select Model | Add Diagram | Sequence Diagram in Menu Bar or select Add Diagram |
Sequence Diagram in Context Menu in Star UML.
7. Create sequence diagrams, showing the interaction between the objects
8. Save the file.
COLLABORATION DIAGRAM
1. This diagram is a numbered transition of sequence diagram in affixed order.

2. The transitions are denoted followed by the operation name.


3. Select Model | Add Diagram | Communication Diagram in Menu Bar or select Add Diagram
| Communication Diagram in Context Menu in Star UML.
4. Create the collaboration diagram, showing numbered transition of sequence diagram
between the objects
5. Save the file.
RESULT

Thus the Sequence and Collaboration diagram was drawn successfully for the Bookbank.
ExNo:6.a
Date: UML-STATE CHART DIAGRAM

AIM :
To draw the state chart diagram for the identified requirements

STATE CHART DIAGRAM :


A State chart diagram describes a state machine. A state machine can be defined as a
machine which defines different states of an object, and these states are controlled by external or
internal events. State chart diagram is used to describe the states of different objects in their life
cycle. So, the emphasis is given on the state changes upon some internal or external events.
These states of objects are important to analyze and implement them accurately. States can be
identified as the condition of objects when a particular event occurs. The state chart diagram
shows the sequence of states that an object goes through during its life in response to outside
message. Set of values that describe an object at a specific point in time.

PROCEDURE
1. Identify important objects to be analyzed.

2. Identify the states.

3. Identify the events.

4. Select Model | Add Diagram | Statechart Diagram in Menu Bar or select Add Diagram |
Statechart Diagram in Context Menu.
5. Create state transition diagram for the project.

6. Use the tools and draw the overall diagram.

7. Save the file.


RESULT

Thus the State chart diagram was drawn successfully for the Bookbank.
ExNo:6.b
Date: UML-ACTIVITY DIAGRAM

AIM :
To draw activity the diagram for the identified requirements .

ACTIVITY DIAGRAM :
An activity diagram is a variation or special case of a state machine, in which the states
are activities representing the performance of operations and the transitions are triggered by the
completion of the operations. Unlike state diagrams that focus on the events occurring to a single
object as it responds to messages, an activity diagram can be used to model an entire business
process. The purpose of an activity diagram is to provide a view of flows and what is going on
inside a use case or among several classes.
An activity is shown as a round box, containing the name of the operation. When an
operation symbol appears within an activity diagram or other state diagram, it indicates the
execution of the operation. Executing a particular step within the diagram represents a state
within the execution of the overall method. It may be applied to any purpose such as visualizing
the steps of a computer algorithm, but is considered especially useful for visualizing business
workflows and processes, or use cases. Some of the outstanding notation includes parallel
activities, swimlanes, and action-object flow relationship. An activity diagram allows the reader
to see the system execution and how it changes direction based upon different conditions and
stimuli.
PROCEDURE
1. Identify the activities, association, conditions and constraints.

2. Name the correct alternative types.

3. It is essential for the diagram to have a start and end points.

4. Select Model | Add Diagram | Activity Diagram in Menu Bar or select Add Diagram |
Activity Diagram in Context Menu in Star UML.
5. Select activity diagram and create activity diagram for requirements of project using the tools.
6. Save the file.
RESULT
Thus the activity diagram was drawn successfully for the Bookbank.
ExNo:7
Date: Implement the system as per the detailed design

Aim :
To implement the Bookbank with database connectivity.

Project Structure:
Source code :

backend/app.js:

import express from 'express'

import { connectdb } from './config/dbconnection.js';

import bookrouter from './routers/bookrouter.js';

import authrouter from './routers/authrouter.js';

import Borrowrouter from './routers/Borrowrouter.js'

import Buyrouter from './routers/buyrouter.js'

import dotenv from 'dotenv'

import cors from 'cors';

import cookieParser from 'cookie-parser';

dotenv.config({ path: 'backend/config/config.env' });

const app=express();

app.use(cors({

origin: 'http://localhost:5173', // allow your React app to access the

API credentials: true, // if you’re using cookies/auth, include this

}));

app.use(cookieParser());

connectdb()

app.use(express.json());

app.use('/api/v1',bookrouter);

app.use('/api/v1',authrouter);

app.use('/api/v1',Borrowrouter);
app.use('/api/v1',Buyrouter)

app.listen(3000,()=>{

console.log("hi im a karthi!");

})

export default app;

backend/authcontroller:

import User from '../model/Auth.js'


import jwt from 'jsonwebtoken';
import sendtoken from '../utils/sendtoken.js';

export const register=async(req,res)=>{

const
{name,email,password,regno,income}=req.body;
const user=await User.create({

name,email,password,regno,income
})

sendtoken(user,200,res)
}

export const login=async(req,res)=>{

const
{email,password,income}=req.body; if(!
email||!password||income){

res.status(404).json({message:"please enter the password"})


}
const user=await User.findOne({email}).select("+password")
if(!user){
return res.status(404).json({
message:"password mismatch"

})
}

sendtoken(user,200,res)

}
export const logout=async(req,res)=>{
const options={expires:new Date(
Date.now()

)
, httpOnly: true}
res.cookie("token",null,options).json({
message:"logut sucessfuly"

})
}

export const getprofile = async (req, res, next) => {


const user = await
User.findById(req?.user?._id); if (!user) {

return res.status(404).json({ message: "Please login first" });

}
console.log("user", user);
res.status(200).json({ user })
;
}

export const allusers=async(req,res,next)=>{


const user=await User.find();

res.status(200).json({
user
})
}

export const getoneuser=async(req,res,next)=>{


const user=await
User.findById(req.params.id);

res.status(200).json({
user

})
}

export const
updateuser=async(req,res,next)=>{ const
updateuser={
name:req.body.name,
email:req.body.email
, role:req.body.role,
}

const user=await User.findByIdAndUpdate(req?.user?._id,updateuser)


res.status(200).json({
user

})
}

export const updateprofile=async(req,res,next)=>{


const resname={
name:req.body.name

}
const user=await User.findByIdAndUpdate(req?.user?._id,resname,{new:true})

res.status(200).json({
user
})

backend/bookcontroller

import Book from '../model/Book.js'; // ✅ Import the model, NOT the seeder
import User from '../model/Auth.js'
import ApiFilter from '../utils/filterapi.js';
export const getbook = async (req, res) => {

try {
const apifilter=new ApiFilter(Book,req.query);
apifilter.search().filters();

;
const books=await apifilter.query;
res.status(200).json({ books});
} catch (err) {

res.status(500).json({ error: err.message });

};
export const newbook = async (req, res) =>
{ console.log("Received data:", req.body);
console.log("Authenticated user:", req.user); // <-- add this

try {

const book = await Book.create({


...req.body,

user: req.user._id, // ✅ required field

});

res.status(200).json({ book });

} catch (err) {
console.error("Book creation error:", err); // <-- log the actual error
res.status(500).json({ error: err.message });
}

};

export const getonebook=async(req,res)=>{


try{
let book=await Book.findById(req.params.id);
let user=await User.findById(req?.user?._id)

res.status(200).json({
book,

user

})
}

catch(err)
{ res.status(500).json({"error":"message"
})

}
}

export const updatebook=async(req,res)=>{


try{
let book=await Book.findById(req.params.id); if(!
book){

return
res.json({ "message":"book not
available"
})
}

book=await Book.findByIdAndUpdate(req.params.id,req.body)
res.status(200).json({

book
})

}
catch(error)
{ res.json({ "mess
sage":"error"

})
}

}
export const deletebook=async(req,res)=>{

let book=await Book.findById(req.params.id); if(!


book){
return
res.json({ "message":"not
available"

})
}

book=await
Book.findByIdAndDelete(req.params.id)
res.status(200).json({
book

})
}
backend/buycontroller.js:

import Stripe from 'stripe';

import Book from


'../model/Book.js'; import Buy from
'../model/Buy.js';

// Hardcode the Stripe secret key (Not recommended for production)


const stripe = new
Stripe('sk_test_51RNE7AB00s9XGWEdsAgleZ2pLCwXTZZyPQHYe7SLUQUXBpLcQHmNRUR7X
HBXp3EyqpsgWSJb3UeCfsLJs83FZM0100nsTTmNgo');

// Create a buy record when a user purchases a book


export const createBuy = async (req, res) => {
try {

const { bookId } = req.body;

if (!bookId) {
return res.status(400).json({ message: 'Book ID is required' });

// Fetch the book to buy

const book = await Book.findById(bookId);

if (!book) {
return res.status(404).json({ message: 'Book not found' });

// Create buy record


const buy = new
Buy({ user:
req.user._id, book:
bookId,
bookDetails:
{ title:
book.title,

author: book.author,
category:
book.category, price:
book.price,
},

userDetails: {
name: req.user.name,
email: req.user.email,
role: req.user.role,
income:
req.user.income,
},

purchaseDate: new Date(),


paymentStatus: 'pending', // update after payment confirmation

});

const createdBuy = await


buy.save();
res.status(201).json(createdBuy);

} catch (error) {
console.error('Error creating buy record:',
error.message); res.status(500).json({ message: 'Server
Error' });
}

};

// Fetch the current user's buy details


export const mybuydetails = async (req, res) => {
try {
// Fetch buy records for the user

const buy = await Buy.find({ user: req.user._id }).populate("book");


res.json({ succes
s: true, data:
buy,
});

} catch (error) {
res.status(500).json({
success: false,

message: error.message,

});
}

};

// Fetch all buy requests


export const allBuyRequests = async (req, res) =>
{ try {
console.log("Fetching all buy requests...");

// Populate both user and book details


const buyRequests = await
Buy.find()
.populate('user', 'name email role income') // Get user details (name, email, role)

.populate('book', 'title author category price'); // Get book details (title, author, etc.)

if (buyRequests.length === 0)
{ console.log("No buy requests
found");

return res.status(404).json({ message: 'No buy requests found' });


}

console.log(`Found ${buyRequests.length} buy


requests`); res.json({
success: true,
data: buyRequests,
});

} catch (error) {
console.error("Error fetching all buy requests:", error);

res.status(500).json({ success: false, message: "Failed to retrieve buy requests" });


}

};

// Approve a buy request


export const requestapproved = async (req, res) =>
{ try {
const buyapproved = await Buy.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json({
data: buyapproved
});
} catch (error) {
res.status(500).json({
success: false,

message: error.message
});

}
};

// Initiate Stripe payment session

export const initiatePayment = async (req, res) =>


{ const { bookId } = req.body;

try {

const book = await Book.findById(bookId);


if (!book) return res.status(404).json({ message: 'Book not found' });
// Determine the success URL based on the environment (development or production)
const successUrl = process.env.NODE_ENV === 'production'
? 'https://yourdomain.com/payment-success?session_id={CHECKOUT_SESSION_ID}'

: 'http://localhost:5173/payment-success?session_id={CHECKOUT_SESSION_ID}';

const session = await


stripe.checkout.sessions.create({ payment_method_types:
['card'],
line_items:
[{ price_data: {
currency: 'usd',
product_data: {

name: book.title,
},

unit_amount: book.price * 100, // Stripe expects amount in cents


},

quantity: 1,
}],

mode: 'payment',
success_url: successUrl,
cancel_url: 'http://localhost:5173/cancel',
});

res.json({ url: session.url });

} catch (error) {
console.error('Error initiating payment:', error.message);
res.status(500).json({ message: 'Error creating payment session' });
}

};
// controllers/paymentController.js
// Example: Express.js route to confirm payment
export const confirmPayment = async (req, res) =>
{ const { sessionId } = req.body;

if (!sessionId) {

return res.status(400).json({ success: false, message: 'Session ID is required' });


}

try {

const session = await stripe.checkout.sessions.retrieve(sessionId);

if (session.payment_status === 'paid') {


// Update the latest pending buy record for this user
const updatedBuy = await
Buy.findOneAndUpdate(
{ user: req.user._id, paymentStatus: 'pending' },

{ paymentStatus: 'paid', paymentSessionId: sessionId },


{ new: true }

);

if (!updatedBuy) {
return res.status(404).json({ success: false, message: 'No pending buy record found to update' });

return res.status(200).json({ success: true, message: 'Payment confirmed and record updated' });
} else {

return res.status(400).json({ success: false, message: 'Payment not completed' });


}
} catch (error) {
console.error('Error confirming payment:', error.message);
return res.status(500).json({ success: false, message: 'Failed to confirm payment' });
}

};

backend/authrouter.js:

import express from 'express';


import { allusers, getoneuser, getprofile, login, logout, register, updateprofile, updateuser } from
'../controller/authcontroller.js';

import { authenticatedrole, isauthentication } from '../middleware/auth.js';

const router=express.Router();
router.route('/books/register').post(register);
router.route('/books/login').post(login)
router.route('/books/logout').post(logout)
router.route("/getprofile/me").get(isauthentication,getprofile)
router.route("/updateprofile").put(isauthentication,updateprofile)
router.route("/admin/allusers").get(isauthentication,authenticatedrole("admin"),allusers)
router.route("/admin/user/:id").get(isauthentication,authenticatedrole("admin"),getoneuser)
router.route("/admin/updateuser/:id").put(isauthentication,authenticatedrole("admin"),updateuser)

export default router;

backend/bookrouter.js

import { getbook,newbook,getonebook,updatebook,deletebook} from


"../controller/bookcontrolller.js"; import express from 'express'
import { isauthentication } from "../middleware/auth.js";

const router=express.Router();
router.route("/books").get(isauthentication,getbook)
router.route("/books").post(isauthentication,newbook)
router.route("/book/:id").get(getonebook)
router.route("/book/:id").put(updatebook)
router.route("/book/:id").delete(deletebook)

export default router;

backend/buyrouter.js

import { allBuyRequests, confirmPayment, createBuy, initiatePayment, mybuydetails, requestapproved


} from "../controller/Buycontroller.js";

import { authenticatedrole, isauthentication } from "../middleware/auth.js";


import express from 'express'

const router = express.Router();

// Route to handle buying a


book
router.route("/books/buy").post(
isauthentication,
authenticatedrole("user","borrower"), // You can adjust roles as needed
createBuy
);

router.route("/books/mybuy").get(isauthentication,mybuydetails)
router.route("/admin/books/requeststatus").get(isauthentication,
authenticatedrole("admin"), allBuyRequests

router.route("/admin/books/requeststatus/:id").put(isauthentication,
requestapproved) router.route('/books/payment').post(isauthentication,
initiatePayment); router.route('/books/confirm-payment').post(isauthentication,
confirmPayment);
export default router;

frontend/app.jsx:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';


import './App.css';

import Header from


'./layout/Header'; import Home from
'./Home';

import Footer from './layout/Footer';


import ProuductDetails from
'./components/ProuductDetails'; import Login from
'./auth/Login';
import Register from './auth/Register';
import Borrow from
'./components/Borrow';
import ReturnBook from './components/ReturnBook';
import Buydetails from './components/Buydetails';
import OrderDetails from
'./components/OrderDetails';
import Buyuserdetails from
'./components/Buyuserdetails'; import Donatebook from
'./components/Donatebook';
import AdminApproved from
'./components/AdminApproved'; import PaymentSuccess from
'./components/PaymentSuccess'; import MyPurchases from
'./components/MyPurchases';
import CollectedPayments from './components/CollectedPayments';

function App() {
return (

<Router className="home-body" >


<div className='bgcolor min-h-screen flex flex-col '>
<Header />
</div>

<main className='flex-grow'>
<Routes>

<Route path='/' element={<Home />} />


<Route path='/book/:id' element={<ProuductDetails />} />

<Route path='/login' element={<Login/>}/>


<Route path='/register' element={<Register/>}/>

<Route path='/borrowdetails' element={<Borrow/>}/>

<Route path='/buydetails' element={<Buydetails/>}/>

<Route path='/returnbook/:id' element={<ReturnBook/>}/>


<Route path='/orderdetails' element={<OrderDetails/>}/>

<Route path="/orders" element={<Buyuserdetails/>}/>


<Route path="/donatebooks" element={<Donatebook/>}/>

<Route path="/AdminApproved" element={<AdminApproved/>}/>


<Route path="/payment-success" element={<PaymentSuccess />} />

<Route path="/purchases" element={<MyPurchases />} />


<Route path="/collected-prices" element={<CollectedPayments />} />

</Routes>
</main>

</Router>

);
}

export default App;


frontend/home.jsx:

import React from 'react';

import { useGetBookQuery } from './redux/api/book.js';


import { useSearchParams, Link } from 'react-router-dom';
// import Filter from './Filter.jsx'; // Uncomment if using Filter

const Home = () => {

const [searchParams] = useSearchParams();


const keyword = searchParams.get('keyword') || '';
const min = searchParams.get('min') || '';
const max = searchParams.get('max') || '';

const { data, isLoading, isError, error } = useGetBookQuery({ keyword, max, min });

// Loading State UI
if (isLoading)
{ return (

<div className="d-flex flex-column align-items-center justify-content-center my-5">


<div className="spinner-border text-primary mb-3" role="status" style={{ width: '3rem', height:
'3rem' }}>
<span className="visually-hidden">Loading...</span>
</div>

<h5 className="text-primary">Loading books, please wait...</h5>


</div>

);
}

// Error (Not Logged In or Server Down) UI


if (isError) {

console.error('API Error:', error);


return (
<div className="container my-5">

<div className="alert alert-danger d-flex align-items-center justify-content-center gap-3 shadow-


sm p-4 rounded" role="alert">
<i className="bi bi-exclamation-triangle-fill fs-4"></i>

<div className="fs-5 fw-semibold">Please login first to view the books.</div>


</div>

</div>
);

// ✅ Book Data Loaded


return (
<div className="container my-5">

{/* Optional Filter */}


{/* <Filter /> */}

<div className="row">

{data?.books && data.books.length > 0 ?


( data.books.map((book) => (

<div className="col-sm-12 col-md-6 col-lg-4 mb-4" key={book._id}>


<div className="card h-100 shadow-sm hover-card border-0 rounded-4">

<img
src={book.image ||
'https://placehold.co/300x200'} className="card-
img-top"
alt={book.title}

style={{ height: '200px', objectFit: 'cover' }}


/>

<div className="card-body d-flex flex-column">


<h5 className="card-title">{book.title}</h5>

<p className="card-subtitle text-muted mb-2">{book.author}</p>


<p className="card-text flex-grow-1">{book.description?.slice(0, 100)}...</p>
<Link to={`/book/${book._id}`} className="btn btn-dark mt-auto w-100">
View Details
</Link>

</div>
</div>

</div>
))

):(
<div className="col-12 text-center">

<p>No books found.</p>


</div>

)}
</div>

</div>
);

};

export default Home;

frontend/productdetails.jsx:

import React from 'react';


import { useGetBookDetailsQuery } from '../redux/api/book';
import { useNavigate, useParams } from 'react-router-dom';
import { useGetBorrowMutation } from '../redux/api/borrowApi';
import { useGetBuyMutation } from '../redux/api/buyApi';

const ProductDetails = () =>


{ const { id } = useParams();
const { data } = useGetBookDetailsQuery(id);
const [getBorrow] =
useGetBorrowMutation(); const [getBuy] =
useGetBuyMutation();
const navigate = useNavigate();

const getborrow = async (e) => {


e.preventDefault();
try {

const res = await getBorrow({ bookId: id }).unwrap();


navigate("/borrowdetails", { state: res });
} catch (err) {
console.error('Borrow Error:', err);
}

};

const buybook = async (e) =>


{ e.preventDefault();
try {

const res = await getBuy({ bookId: id }).unwrap();


navigate("/buydetails", { state: res });

} catch (err) {
console.error('Buy Error:', err);

}
};

return (

<div className="container my-5">


<div className="row justify-content-center">

<div className="col-lg-10">
<div className="card shadow-lg border-0 rounded-4 overflow-hidden">
<div className="row g-0">
<div className="col-md-5 bg-light d-flex align-items-center justify-content-center p-4">

<img
src={data?.book?.image}
alt="Book"

className="img-fluid rounded shadow-sm"


style={{ maxHeight: '400px', objectFit: 'contain' }}
/>

</div>

<div className="col-md-7 p-4">

<h2 className="fw-bold mb-2">{data?.book?.title}</h2>


<h5 className="text-muted mb-3">by {data?.book?.author}</h5>

<p><strong>ISBN:</strong> {data?.book?.isbn}</p>
<p><strong>Category:</strong> {data?.book?.category}</p>

<p className="fs-4 text-primary fw-semibold">


${data?.book?.price}

</p>
<div className="d-flex gap-3 mt-4">

<button
className="btn btn-outline-secondary btn-lg px-4 shadow-sm"
onClick={getborrow}
>

<i className="bi bi-book"></i> Borrow


</button>

<button

className="btn btn-primary btn-lg px-4 shadow-sm"


onClick={buybook}
>

<i className="bi bi-cart4"></i> Buy Now


</button>
</div>
</div>

</div>
</div>

</div>
</div>

</div>
);

};

export default ProductDetails;

OUTPUT:

USER REGISTRATION AND LOGIN


BOOK REQUEST:
BOOK STATUS:

ADMIN LOGIN:
REQUEST APPROVAL:
PAYMENT PROCESS:
COLLECTED PAYMENTS:

Result:

Thus the implementation for the Bookbank with database connectivity was
completed.
ExNo: 8
Date: Test the software system for all the scenarios identified as per the usecase diagram

Aim :
To test the software system for all the scenarios identified as per the use case diagram.

Testing :

Black box testing:


Black box testing, also known as basic testing or specification-based testing, is a software testing
method that focuses on an application&#39;s functionality without looking at its internal structure or
workings.

Decision table testing :


Decision table testing is a black box test design technique that uses decision tables to design test
cases. A decision table is a visual representation of the actions to perform based on given
conditions or inputs.

Black Box Testing – Decision Tables (AAMEC BookBank) :

Test Case Email Password Expected Output Actual Output Res


ID ult
TC_LP_0 Valid Valid Redirect to Account Redirect to Account Pass
1 Email Password Page Page
TC_LP_0 Valid Invalid Error: Incorrect Error: Incorrect Pass
2 Email Password password password
TC_LP_0 Invalid Valid Error: Invalid email Error: Invalid email Pass
3 Email Password
TC_LP_0 Invalid Invalid Error: Invalid email Error: Invalid email Pass
4 Email Password and password and password
TC_LP_0 Empty Valid Error: Email required Error: Email required Pass
5 Email Password
TC_LP_0 Valid Empty Error: Password Error: Password Pass
6 Email Password required required
TC_LP_0 Empty Empty Error: Fields required Error: Fields required Pass
7 Email Password
Decision Table 2 – Book Request Page

Test Case Book Student Expected Actual


ID ID ID Output Output
Exists Valid
TC_BR_01 Yes Yes Request Request
successful successful
TC_BR_02 Yes No Error: Error:
Invalid Invalid
student student
ID ID
TC_BR_03 No Yes Error: Error:
Book not Book not
available available
TC_BR_04 No No Error: Error:
Book not Book not
available, available,
Invalid Invalid
student student
ID ID
TC_BR_05 Yes Empty Error: Error:
Student Student
ID ID
required Required

Decision Table 3– Admin Login

Test Case ID Username Password Expected Output Actual Output Result


Valid Admin dashboard is Admin dashboard is
TC_AL_01 Valid Admin Pass
Password displayed displayed
Invalid
TC_AL_02 Valid Admin Error: Incorrect password Error: Incorrect password Pass
Password
Valid
TC_AL_03 Invalid Admin Error: Invalid username Error: Invalid username Pass
Password
TC_AL_04 Invalid Invalid Error: Invalid username Error: Invalid username Pass
Valid
TC_AL_05 (Empty) Error: Username required Error: Username required Pass
Password
TC_AL_06 Valid Admin (Empty) Error: Password required Error: Password required Pass
Error: Username and Error: Username and
TC_AL_07 (Empty) (Empty) Pass
password required password required
Decision Table 4: Book Issue Page

Test Case Student Book Expected Actual Output Result


ID Logged Available Output
In
TC_BI_01 Logged Available Book issued Book issued Pass
In successfully successfully
TC_BI_02 Logged Not Error: Book not Error: Book not Pass
In Available available available
TC_BI_03 Not Available Error: Student Error: Student Pass
Logged must be logged must be logged
In in in
TC_BI_04 Not Not Error: Student Error: Student Pass
Logged Available must be logged must be logged
In in, Book not in, Book not
available available
TC_BI_05 Logged Empty Error: No book Error: No book Pass
In selected selected

JEST TESTING TOOL


Jest is a testing framework for JavaScript, primarily designed for testing React applications, but it can be
used with any JavaScript code. It is widely used in the JavaScript community due to its ease of use and
powerful features.\Why Use Jest?

Key Features of Jest:


Zero Configuration: Jest works out of the box with no setup, making it easy to get started with testing.

Test Runner: Jest runs tests concurrently to speed up execution and provides detailed output and
reporting.

Assertions Library: Jest comes with built-in assertions like toBe, toEqual, and more, allowing you to
check the expected values.

Mocking: Jest has powerful mocking capabilities, which help simulate and replace dependencies during
testing.

Snapshot Testing: It allows you to capture the output of React components and compare it over time,
helping you catch unexpected changes.

Code Coverage: Jest can automatically generate code coverage reports, helping you ensure that your tests
are covering the necessary parts of your code.
Zero Configuration: Works out of the box with minimal setup.
Fast and Efficient: Runs tests in parallel for improved
performance. Snapshot Testing: Helps track UI changes over time.

Mocking Capabilities: Easily mocks functions, modules, and


APIs. Code Coverage: Provides insights into untested parts of your
code.
Login Page:
Result :
Thus the test of software system for all the scenarios identified as per the use case diagram using
black box and jtest testing was executed .
ExNo:9
&10 Date Improve the reusability and maintainability of the software system by
applying appropriate design patterns test it for various scenarios

Aim :

To Improve the reusability and maintainability of the software system by applying appropriate
design patterns and test it for various scenarios.

Design Pattern- MVC


MVC-description

The MVC framework separates an application into three main components: models,
views, and controllers. Models are used to store data and business logic; views display data from
a model on the screen; and controllers manage user interactions with these two components.

Model
The Model component corresponds to all the data-related logic that the user works with. This can
represent either the data that is being transferred between the View and Controller components or any
other business logic-related data. For example, a Customer object will retrieve the customer
information from the database, manipulate it and update it data back to the database or use it to render
data.

View
The View component is used for all the UI logic of the application. For example, the Customer view
will include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with.

Controller
Controllers act as an interface between Model and View components to process all the business logic
and incoming requests, manipulate data using the Model component and interact with the Views to
render the final output. For example, the Customer controller will handle all the interactions and
inputs from the Customer View and update the database using the Customer Model. The same
controller will be used to view the Customer data.
Result:
Thus, the reusability and maintainability of the software system was improved by applying
appropriate design pattern and tested for various scenarios successfully.
ExNo:11
Date: DATA FLOW DIAGRAM

To identify Data flow diagram and develop a DFD modelwith Star UML.

Data flow diagram :

 A graphical tool, useful for communicating with users, managers, and other personnel .
 Used to perform structured analysis to determine logical requirements .
 Useful for analyzing existing as well as proposed systems.
 Focus on the movement of data between external entities and processes, and
between processes and data stores .
 A relatively simple technique to learn and use.

Procedure:

Step : 1
Open StarUML 5.0: Launch the StarUML application on your computer.

Step : 2
Create a New Project: Start a new project by clicking on "File" > "New" > "Project" or by using the
shortcut Ctrl + N.

Step : 3
Add a Data Flow Diagram: Once the project is created, go to "Model" > "Add Diagram" > "Data
Flow Diagram".

Step : 4
Name the Diagram: Give your diagram a name, like " Recruitment System DFD".

Step : 5
Identify External Entities: Identify the external entities involved in the recruitment process.
These could include job applicants, recruiters, and the HR department.

Step : 6
Add Processes: Identify the main processes involved in the recruitment process, such as "Receive
Application", "Screen Candidates", "Schedule Interviews", "Conduct Interviews", and "Offer Job".

Step : 7
Add Data Stores: Identify where data is stored during the process. This could include databases for
storing applicant information, resumes, and interview feedback.
Step : 8
Draw Data Flows: Connect the processes, external entities, and data stores using data
flows. Data flows represent the flow of information between different elements of the
system.

Step : 9
Define Data Flow Names: Label the data flows with meaningful names to describe the
information being passed between elements.

Step : 10
Save Your Work: Once you're satisfied with the diagram, save your work by clicking on
"File" > "Save" or using the shortcut Ctrl + S.
DFD FOR BOOKBANK:

BOOKBANK

BOOK BANK

Level 1
RESULT :

Thus the Data flow diagram was drawn successfully for the Bookbank.

You might also like