Asm2 1622
Asm2 1622
Unit number and title Unit 04: Database Design & Development
Student declaration
I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand that
making a false declaration is a form of malpractice.
Grading grid
P2 P3 P4 P5 M2 M3 M4 M5 D2 D3
❒ Summative Feedback: ❒ Resubmission Feedback:
Figure 1: My Database
1.1 Final Mock-up of the application
The login form is a place where members of FPT Shop company can log in to manage their accounts, and it is also where clients can
log in to purchase items
- The first and most important step is to create the database table.
Based on user requirements, the update commands must adhere to their demands, including updating product information, updating
customer information, and updating manager information.
- Updating product information includes updating product name, product details, product price, and inventory
For example 1, for product with ID = 1, I will update the product details, product price, and inventory quantity.
However, the product name will remain unchanged
This statement is used to update the product table in a database. The specific product that will be updated is identified by its
product_id, which is set to 1 in this case. The statement updates three fields of the product record: description, price, and
quantityInStock.
The SET clause lists the fields that will be updated and their new values. In this case, the description field is being updated to 'One of
the phones with the most powerful chipset', the price field is being updated to '999.99', and the quantityInStock field is being updated
to '55'.
The WHERE clause specifies which product record to update. In this case, only the record with a product_id of 1 will be updated. If
you omit the WHERE clause, all records in the product table will be updated with the new values, which could have unintended
consequences.
For example 2, for product with ID = 2, I will update the product price and inventory quantity in case the product has
been released for a long time and the demand for it has cooled down, and the number of products in stock has
decreased or increased
This UPDATE statement is also updating the product table in a database, specifically updating the price and quantityInStock fields for
a product with a product_id of 2.
The SET clause lists the fields that will be updated and their new values. In this case, the price field is being updated to '898.99' and
the quantityInStock field is being updated to '35'.
The WHERE clause specifies which product record to update based on the condition provided. In this case, only the record with a
product_id of 2 will be updated with the new values.
- Updating customer information includes updating first name, last name, phone number, and email
For example, for customer with ID = 1, they may have entered incorrect information when registering, so they want to
correct their name, phone number, and email
This UPDATE statement is updating the client table in a database, specifically updating the firstName, lastName, phone, and email
fields for a client with a client_id of 1. The SET clause lists the fields that will be updated and their new values. In this case, the
firstName field is being updated to 'Robert', the lastName field is being updated to 'Dao', the phone field is being updated to
'0373019563', and the email field is being updated to '[email protected]'.
- Updating manager information includes updating first name, last name, phone number, and email
For example, for manager with ID = 3, they recently lost their phone along with their phone number, so they have obtained a new
phone number and want to update their phone number
This UPDATE statement is updating the manager table in a database, specifically updating the phone field for a manager with a
manager_id of 2. The SET clause lists the fields that will be updated and their new values. In this case, only the phone field is being
updated to '0367599875'.
As per the user's request, the delete function will be applied to a product when it is no longer sold in the shop. Additionally, in the case
where a manager's contract ends or they are no longer working at the company, their account will also be deleted to prevent the loss of
shop information such as customer or product information.
- Example 1, Delete the manager with ID = 6 because they have resigned from the company
The FROM keyword specifies the name of the table from which records should be deleted, which in this case is the manager table.
The WHERE clause is used to specify which records should be deleted. In this statement, the condition is that the manager_id field
must be equal to 6.
When this SQL statement is executed, the database will locate all records in the manager table where manager_id equals 6.
If there are any records that match this condition, they will be permanently deleted from the manager table.
It's important to note that this action cannot be undone, so it's important to double-check that you're deleting the correct records before
executing the statement.
- Example, Delete the product with ID = 8 as this product is no longer sold in the shop.
The FROM keyword specifies the name of the table from which records should be deleted, which in this case is the product table.
The WHERE clause is used to specify which records should be deleted. In this statement, the condition is that the product_id field
must be equal to 8.
When this SQL statement is executed, the database will locate all records in the product table where product_id equals 8.
If there are any records that match this condition, they will be permanently deleted from the product table.
It's important to note that this action cannot be undone, so it's important to double-check that you're deleting the correct records before
executing the statement.
Based on the user's requirements, I will adhere to them to apply the appropriate adjustment.
SELECT DISTINCT c.* selects all columns from the client table, and DISTINCT ensures that each client record is returned only once
even if they have multiple orders containing the specified product.
The INNER JOIN keyword is used to join the client table with the order table based on the client_id field.
Another INNER JOIN is used to join the order_item table with the previous join based on the order_id field.
The WHERE clause is used to filter the results to only show customers who have purchased a specific product, which is specified
using the product_id field in the order_item table.
Replace <product_id> with the ID of the product user want to search for, and this SQL statement will return a list of all customers
who have purchased that product.
The SELECT clause uses the SUM function to calculate the total profit, which is the sum of the product of the quantity and price of
each product sold. The alias profit is used to label this calculated value.
oi.quantity is the quantity of a specific product that has been ordered, and p.price is the price of that product.
oi.quantity * p.price is the total revenue from selling that specific product.
By using SUM(oi.quantity * p.price) for all products sold, you get the total revenue from all product sales.
The FROM clause specifies the tables that you want to query. In this case, you are querying the product table and joining it with the
order_item table.
The INNER JOIN keyword is used to join the product and order_item tables based on the product_id field.
The ON clause specifies the condition for joining the tables, which is that the product_id field in the product table must match the
product_id field in the order_item table.
3. Find the orders managed by a Manager
The SELECT clause specifies the fields that you want to retrieve from the order table. You can replace * with the specific fields that
you are interested in.
The FROM clause specifies the tables that you want to query. In this case, you are querying the order table and joining it with the
manager table.
The INNER JOIN keyword is used to join the order and manager tables based on the manager_id field.
The ON clause specifies the condition for joining the tables, which is that the manager_id field in the order table must match the
manager_id field in the manager table.
The SELECT clause specifies the columns that you want to retrieve, which are client_id, firstName, and lastName from the client
table.
The FROM clause specifies the tables that you want to query, which are the client and order tables.
The INNER JOIN keyword is used to join the client and order tables based on the client_id field.
The GROUP BY clause is used to group the results by client_id, firstName, and lastName of the client table.
The HAVING clause filters the results to only include clients who have made 3 or more orders. The COUNT(o.order_id) function is
used to count the number of orders made by each client, and the >= operator is used to filter the results to only include clients who
have made 3 or more orders.
5. Return the average time difference from the order date to the shipping date for each type of product order status
This line specifies the columns that should be returned in the results: order_id and the average time difference, which is calculated
using the AVG() function and the DATEDIFF() function.
DATEDIFF() is used to calculate the difference in days between the order date (o.orderDate) and the shipped date (o.shippedDate).
day should actually be o.shippedDate to get the correct results. The result of the DATEDIFF() function is then passed to the AVG()
function, which calculates the average time difference across all orders.
These lines specify the tables that are being used in the query and how they are joined.
orders is the main table that contains order information, while order_item and product are joined to get the product information
associated with each order item.
The INNER JOIN clause is used to join the tables based on the common order_id and product_id columns.
In this case, the results are grouped by order_id, which means that the average time difference is calculated for each unique order_id.
This ensures that the query returns one row per order, with the average time difference for each order.
2.5 Advanced queries: Stored procedures, scalor functions
a. Scalor functions
- A scalar function to retrieve a list of products that have been ordered by a specific customer. Ensure that this scalar function
only returns results for users with access rights as manager.
-
Explanation:
CREATE FUNCTION GetOrderedProductsByCustomer (@customerId INT) - Declare a Scalar Function with the name
GetOrderedProductsByCustomer, which takes one argument customerId.
RETURNS VARCHAR(MAX) - Specifies the return data type of the function as VARCHAR with a maximum size of MAX.
DECLARE @result VARCHAR(MAX) - Declare a variable @result of data type VARCHAR with maximum size of MAX.
IF (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE is_user_ process = 1 AND original_login_name = 'manager') = 0 -
Checks if the authenticated user has manager access by checking the number running instance (sessions) in SQL Server, if it is 0, user
is not allowed to execute Function.
SET @result = 'Unauthenticated user as manager.' - Assign the error message string to the @result variable.
RETURN @result - Returns the value of the @result variable and ends the execution of the Function.
SELECT @result = COALESCE(@result + ', ', '') + p.product_name FROM order o JOIN order_item oi ON o.order_id = oi.order_id
JOIN product p ON oi.product_id = p.product_id JOIN GIA customer c ON o .client_id = c.client_id WHERE c.client_id =
@customerId - Execute a SQL query to get a list of products ordered by a customer with the specified customer id.
RETURN @result - Returns the ordered list of products as a string and ends the execution of the Function.
GO - Function termination marker and separator between different SQL statements in the script.
- Create a stored procedure to delete a product. Ensure that this stored procedure only executes when an authenticated user is a
manager.
Explanation:
CREATE PROCEDURE DeleteProduct @productId INT - This is a command to create a new stored procedure named
"DeleteProduct" with an input parameter named "productId" of data type INT.
RAISERROR('User not authenticated as a manager.', 16, 1) - Returns an error message if the user is not authenticated.
DELETE FROM product WHERE product_id = @productId - Deletes a product from the "product" table based on the passed-in
"productId".
This command executes the stored procedure called Delete Product with the product id value of 8.
c. Trigger
- Create a trigger to check the quantity of products in stock before adding a new order and raise an error message if the quantity
of products in stock is not sufficient to fulfill the order.
This code creates a trigger on the order_item table and is fired every time a record is added to the table. This trigger checks the number
of products in stock before adding a new order. If the number of products in stock is less than the ordered quantity, the trigger will issue
an error message and rollback the transaction to ensure that the data has not been changed. If there is no problem, the number of products
left in stock will be updated.
Line 1: Create a CheckInventory trigger on the order_item table, use AFTER INSERT to fire the trigger after a new record is added.
Lines 3-13: The trigger uses a temporary variable @productId to store the ID of the product in the newly added order_item record, and
a temporary @quantityInStock to store the number of products left in stock. The temporary variable @sales is used to store the number
of products ordered in the newly added record.
Line 4: Get the number of products ordered in the newly added record.
Lines 5-8: Get the product ID and the number of products left in stock from the product table.
Lines 9-13: Check the number of products left in stock. If the quantity in stock is less than the ordered quantity, the trigger will issue an
error message and rollback the transaction.
Lines 15-18: If there are no problems, the number of products left in stock will be updated by subtracting the number of products ordered.
Updates are performed on the product table using the UPDATE statement.
- Use Trigger
I will insert a new order with a quantity of products that exceeds the quantity of products in stock. For example, I will insert an order
with an ID of 11 and a product ID of 8 with an order quantity of 20, even though there are only 11 products left in stock.
The program will report an error because simply the products in the inventory are not sufficient in quantity to fulfill the customer's
order.
2.6 Evaluate the effectiveness of the database solution
In my database, all necessary entities and fields are available for users to utilize, such as managing employees, products, customers,
and their orders, allowing executives to run the company efficiently. Managers can also manage products, customers, and their orders.
Additionally, customers can purchase products, update their information, and provide feedback on their orders. However, these are all
basic functionalities, and my database has yet to implement any advanced performance optimizations. Despite being incomplete, I will
strive to improve it to the best of my knowledge and abilities.
To ensure that all commands adhere to user requirements, we have decided to plan to re-test all results of the functions and commands
above that we have set up, and ensure that the program operates as smoothly as possible and has no errors to be delivered to the end
user. Below is the order of our test cases and the reasons why we selected these cases for testing:
-Deleting an employee is one of the important functions of the FPT company system, which aims to ensure system safety to prevent
specific employee data from leaking out when this employee, in this case a manager, no longer works for the company.
-Deleting a product is a function for users to delete a product when the company no longer sells it, either because it is not suitable for
their field or for some other reason.
-Our program aims to store customer information to add potential customers, so there is no function to delete customers.
-Inserting an employee, in this case a manager, is a function used when someone successfully applies to the company and will be
added to the system by the director.
-Inserting a product is an important function of the system to ensure that the company has new products, and that these products will
be added to the system by the manager.
-Inserting feedback is a customer function when they have purchased a product and want to provide feedback on their reaction when
receiving the order.
-Updating customer information is a fairly important function used when customers want to update their phone number or email, or
when they register their name incorrectly.
-Getting a list of products that have been ordered by a specific customer, returning the result to the manager, checking the operation of
the void function. This is easy for the company manager to know which customers are potential customers.
-Getting a list of products that have been ordered by a specific customer, returning the result to the customer, checking the operation
of the void function. I want to check the system's security and privacy through whether the customer can view the company's
information or not.
-Deleting a product is executed when the requester is a manager. I want to check the security through the requester of the command.
-Deleting a product is executed when the requester is a client. I want to check the security through the requester of the command.
-Checking the quantity of products in stock when adding a new order, if the order quantity of the product is greater than the quantity
of the product in stock, an error message will be displayed.
NO. TEST CASE INPUT DATA EXPECTED RESULT ACTUALY RESULTS STATUS
DESCRIPTION
1 Deleting an ID = 6 1 row affected 1 row affected Pass
employee, in this
case a manager
2 Deleting a product Product_ID = 8 1 row affected 1 row affected Pass
3 Inserting an Manager_id="6", first A new manager record is A new Order record is Pass
employee, in this name = Robert, last name added to the database with added to the database with
case a manager = Dao, phone = the above input data the above input data
0373019563, email =
[email protected],
director_id = 1
4 Inserting a product Product_ID=1, Name=" A new Product record is A new Product record is Pass
iPhone 14 Pro ", added to the database with added to the database with
Description=" Latest high- the above input data the above input data
end smartphone from
Apple A", Price= 1099.99,
QuantityInStock = 100
5 Inserting feedback Feedback_id = 2, The procedure returns an The procedure returns an Pass
comment=" Could be error message saying that error message saying that
better ", Client_ID=1, the Client_ID is invalid the Client_ID is invalid
Order_ID=2
6 Updating customer Order_ID=10, first name = Update successfully from Update successfully from Pass
information Diana, last name = email = email =
Nguyen, phone = [email protected] to [email protected] to
11111122231, email = phone = 0399872898, email phone = 0399872898,
[email protected] = email =
update to first name = [email protected] [email protected]
Diana, last name =
Nguyen, phone =
0399872898, email =
[email protected]
7 Getting a list of client_id = 8 Iphone 14 pro, Dell XPS 13 Iphone 14 pro, Dell XPS Pass
products that have 13
been ordered by a
specific customer,
returning the result to
the manager
8 Getting a list of client_id = 7 User not authenticated as User not authenticated as Pass
a manager. a manager.
products that have
been ordered by a
specific customer,
returning the result to
the customer
9 Deleting a product is Product_id = 8 Deleting product with id = 8 Deleting product with id = Pass
executed when the successfull 8 successfull
requester is a
manager
10 Deleting a product is Product_id = 7 User not authenticated as User not authenticated as Pass
a manager. a manager.
executed when the
requester is a client
11 Checking the Feedback_id = 2, The procedure returns an The procedure returns an Pass
quantity of products comment=" Could be error message saying that error message saying that
in stock when adding better ", Client_ID=1, the Client_ID is invalid the Client_ID is invalid
a new order Order_ID=2
For customers: To log in to the system, users must have an account for customers, including email and password. Additionally, if
customers do not have an account to log in to the system, they must provide information such as name, phone number, address, email
address to register for an account. After the system receives accurate information, users will be redirected to the product purchase
page. When there are products in the shopping cart and customers want to buy them, the system will redirect customers to the payment
page, where consumers can check the accuracy of the product and view data such as price and quantity. After completing the payment,
consumers will receive an invoice and can give feedback on the quality of the product after receiving it in their hands.
For managers: Managers must have a login account including email and password provided by the director to access the system. After
logging in, managers will be redirected to the manager page. Managers can retrieve information about Products, Invoices, Stores,
Orders and Customers through the management page. Managers can add, update, and delete records in the system regarding products.
For the Director: To have access to the system, the Director must also have an account with an email and password. After the Director
logs into the system, the system will redirect to the Director page. The Director is the highest authority and has access to all
information systems, allowing them to monitor all managers. Direct access provides system functions, including the ability to add,
modify, and delete data.
3.2.2 Flowchart
a. Flowchart of system
Insert:
-Input data
-Check
c. Update Function
-Input data
–Check
c. Delete function
Figure 23: Delete Function
Delete: