0% found this document useful (0 votes)
22 views56 pages

clc03 Hmtoan Ass4

The document outlines an assignment on the analysis and design of an e-commerce system using microservices and Django, detailing requirements, system architecture, and AI applications. It includes chapters on requirements determination, system design, AI integration, and implementation specifics, with a focus on user roles, service components, and RESTful API design. The document emphasizes scalability, maintainability, and the use of deep learning for enhancing e-commerce functionalities.

Uploaded by

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

clc03 Hmtoan Ass4

The document outlines an assignment on the analysis and design of an e-commerce system using microservices and Django, detailing requirements, system architecture, and AI applications. It includes chapters on requirements determination, system design, AI integration, and implementation specifics, with a focus on user roles, service components, and RESTful API design. The document emphasizes scalability, maintainability, and the use of deep learning for enhancing e-commerce functionalities.

Uploaded by

vuhuyhoang12abm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

HỌC VIỆN CÔNG NGHỆ BƯU CHÍNH VIỄN

THÔNG
KHOA CÔNG NGHỆ THÔNG TIN

Assignment 4 Analysis Design


E-Commerce
Name: Hoang Minh Toan
ID: B21DCCN713
Class : D21CNPM03
Teacher : Tran Dinh Que
Chapter 1 : Requirements Of Commerce...................................................... 3
I. Determine requirement..............................................................................3
1. Actors.................................................................................................. 3
2. Functions with Respect to Actors........................................................ 3
3. Use Case Diagram.............................................................................. 4
II. Analyze Requirements............................................................................. 4
1. Decompose the system in microservices with Django........................ 4
2. Classes with attributes of service models........................................... 5
3. Determine functions in services.......................................................... 8
4. Determine templates........................................................................... 9
Chapter 2 : Design E-Commerce System With Microservices and Django.
11
1. Design Service/ Components................................................................. 11
2. Design Classes and Method in Each Component.................................. 11
3. Design API............................................................................................. 12
4. Conclusion..............................................................................................13
Chapter 3 : AI In E-Commerce......................................................................24
1. Application of Deep Learning in E-commerce........................................ 24
2. Sentiment Analysis................................................................................. 25
3. Applying Sentiment Analysis for Recommendation ​
Integrating sentiment analysis enhances personalization and product
quality feedback in recommendations........................................................ 25
4. Deployment............................................................................................ 26
5. Conclusion..............................................................................................27
Chapter 4 Implementation and deployment................................................28
Models.py.............................................................................................. 29
Serializers.py......................................................................................... 35
views.py.................................................................................................37
Urls.py................................................................................................... 41
Templates.............................................................................................. 43
Running................................................................................................. 49

1
Chapter 1 : Requirements Of Commerce
I.​ Determine requirement
1.​Actors

Actor Description

Customer End-user who browses items, places


orders, and makes payments

Order Staff Handles product management,


inventory, and order processing

Delivery Staff Responsible for delivering orders to


customers

Admin System manager, handles overall


configurations and data
management

Provider General entity providing items;


information only (read-only class)

Publisher Provides books; used as an


informational reference (read-only)

Producer Provides electronic devices; used as


informational reference (read-only)

Bank Participates in online payments

2.​Functions with Respect to Actors

Actor Description

Customer Register/Login, Browse Items, Add


to Cart, Checkout, Pay, Track Orders

Order Staff View/Approve/Reject Orders, Update


Order Status, Add/Edit Products,

2
Add/Edit Books, Manage Inventory,
Add/Edit Electronic Devices

Delivery Staff View Deliveries, Update Delivery


Status

Admin Manage Customers, Staff, Items,


Orders, Payments, Shipping, and
Provider/Publisher/Producer Info

Provider Provides reference data only

Publisher Add/Edit Books, Manage Inventory

Producer Provides reference data only

Bank Handle payment validation and


refunds

3.​Use Case Diagram

3
II. Analyze Requirements

1.​Decompose the system in microservices with Django

Microservice App Responsibility

Customer Service User registration, login, profiles

Item Service Generic item handling (base model


for books, devices)

Cart Service Manages shopping carts

Order Service Handles order creation and


processing

Payment Service Manages payments

Bank Service Simulates bank/payment validation

Shipping Service Tracks delivery and shipment info

Staff Service Handles order and delivery staff

Book Service Extends item model; manages


book-specific metadata​

Electronic Service Extends item model; manages


electronic-specific metadata

Admin Panel Manages Provider, Publisher,


Producer info

2.​Classes with attributes of service models

Class Attribute

Customer ID, Name, Email, Password, Phone,


Address

Item ID, Name, Category, Price, Stock,


Provider

4
Cart Customer, Item, Quantity

Order Customer, Order Date, Status, Total


Amount

Payment Linked Order, Payment Method,


Transaction ID, Payment Status

Bank Simulates bank/payment validation

Shipping Order, Delivery Address (Address


class), Status, Tracking Number

Staff ID, Name , Role (order/delivery),


Contact Info

Book Linked Item, Title, Author, Publisher


(reference), ISBN​

Electronic Device Linked Item, Specifications, Warranty


Period, Producer , Provider

Name Family Name, Last Name, Name

Address Nation, City, Province, Street, House


Number, Office Code

Admin Panel Manages Provider, Publisher,


Producer info

Provider Name, Address (Address class),


Phone

Publisher Name, Address (Address class),


Phone

Producer Name, Address (Address class),


Phone

Customer
ID: Integer (AutoField)
Name: Name (Object)
Email: Email (String)
Password: String
Phone: String
Address: Address (Object)

5
Item
ID: Integer (AutoField)
Name: String
Category: String
Price: Decimal
Stock: Integer
Provider: Provider (Reference)

Cart
Customer: Customer (Reference)
Item: Item (Reference)
Quantity: Integer

Order
Customer: Customer (Reference)
Order Date: DateTime
Status: String
Total Amount: Decimal

Payment
Order: Order (Reference)
Payment Method: String
Transaction ID: String
Payment Status: String

BankTransaction
ID: Integer (AutoField)
Order: Order (Reference)
Transaction ID: String
Status: String
Timestamp: DateTime

Shipping
Order: Order (Reference)
Delivery Address: Address (Object)
Status: String
Tracking Number: String

Staff
ID: Integer (AutoField)

6
Name: Name (Object)
Role: String ("order", "delivery", etc.)
Contact Info: String

Book
Linked Item: Item (OneToOne)
Title: String
Author: String
Publisher: Publisher (Reference)
ISBN: String

Electronic Device
Linked Item: Item (OneToOne)
Specifications: Text
Warranty Period: String
Producer: Producer (Reference)
Provider: Provider (Reference)

Name
Family Name: String
Last Name: String
Name: String

Address
Nation: String
City: String
Province: String
Street: String
House Number: String
Office Code: String

Admin
ID: Integer (AutoField)
Name: Name (Object)
Email: Email
Password: String
Phone: String

Provider / Publisher / Producer


Name: String

7
Address: Address (Object)
Phone: String

3.​Determine functions in services

Class Function

Customer register_customer(),
login_customer(), view_profile(),
edit_profile()

Item add_item(), edit_item(),


delete_item(), list_items()

Cart add_to_cart(), view_cart(),


remove_from_cart(),
update_quantity()

Order place_order(), view_order(),


update_order_status(),
cancel_order()

Payment initiate_payment(),
confirm_payment(),
view_payment_status()

Bank validate_payment(),
process_refund()

Shipping assign_delivery(),
update_shipping_status(),
track_order()

Staff login_staff(), view_assigned_tasks(),


update_task_status()

Book add_book(), edit_book(),


list_books(), delete_book()

Electronic Device add_device(), edit_device(),


list_devices(), delete_device()

Name get(), update()

Address get(), update()

8
Admin Panel add_publisher(), edit_provider(),
delete_producer(),
list_all_metadata()

Provider get()

Publisher get(), update()

Producer get(), update()

4.​Determine templates
Customer-facing template

Template file Description

register.html User registration form for customers

login.html Login page (for customer, staff, or


admin, with role switch)

home.html Homepage displaying featured items


or categories

product_list.html View all items with filters for


books/electronics/categories

product_detail.html View item details and add to cart

cart.html Displays items in customer cart

checkout.html Shipping, payment, and order


confirmation summary

order_status.html Shows current status of all customer


orders

profile.html Customer profile view/edit

Order Staff templates

Template file Description

staff_dashboard.html Overview dashboard for order staff

add_item.html Form to add a general product

9
edit_item.html Form to update general product
information

add_book.html Form to create a new book (extends


item)

edit_book.html Edit book-specific attributes

add_device.html Form to create a new electronic


device

edit_device.html Edit electronic device attributes,


including provider/producer

inventory_list.html Displays current stock levels for all


items

order_list_staff.html View and manage orders from staff


perspective

Delivery Staff Templates

Template files Description

delivery_dashboard.html Overview of assigned deliveries

delivery_list.html List of delivery tasks assigned

update_delivery.html Update delivery status and mark as


completed

Admin Templates

Template File Description

admin_dashboard.html Main control panel for admin users

manage_users.html View/edit/delete customer or staff


accounts

provider_list.html View/manage providers

add_provider.html Add new provider (name, address,


phone)

publisher_list.html View/manage book publishers

10
add_publisher.html Add a new publisher

producer_list.html View/manage electronics producers

add_producer.html Add new producer with address and


contact

system_report.html Summary charts or logs (optional)

Shared templates

Template file Description

base.html Main layout template with


navigation/header/footer

form.html Reusable template for form


rendering

message.html Success, error, and alert messages

404.html, 500.html Custom error pages

Chapter 2 : Design E-Commerce System With


Microservices and Django
1.​Design Service/ Components

Component Responsiblity

Customer Service Manages customer registration,


login, and profile info

Item Service Handles base items and general


product listing

Book Service Manages book-specific logic


(extends item)

Electronic Device Handles electronics (extends item),

11
links to both Producer and Provider

Cart Service Manages shopping cart operations


for customers

Order Service Handles order creation, tracking, and


status updates

Payment Service Initiates and verifies payments

Bank Service Simulates third-party bank/payment


validation

Shipping Service Handles delivery and shipping status

Staff Service Manages order and delivery staff


operations

Admin Panel Manages metadata for Provider,


Publisher, and Producer

2.​Design Classes and Method in Each Component

Component Class and methods

Customer Service Customer : register_customer(),


login_customer(). view_profile(),
edit_profile()
Name , Class

Item Service Item: add_item(), edit_item(),


delete_item(), list_items()

Book Service Book: add_book(), edit_book(),


list_books(), delete_book()

Electronic Device ElectronicDevice: add_device(),


edit_device(), list_devices(),
delete_device()

Cart Service Cart : add_to_cart(), view_cart(),


remove_from_cart(),
update_quantity()

12
Order Service Order: place_order(), view_order(),
update_order_status(),
cancel_order()

Payment Service Payment: initiate_payment(),


confirm_payment(),
view_payment_status()

Bank Service TransactionLog: validate_payment(),


process_refund()

Shipping Service Shipping : assign_delivery(),


update_shipping_status(),
track_order()

Staff Service Staff: login_staff(),


view_assigned_tasks(),
update_task_status()

Admin Panel Provider, Publisher, Producer:


add_publisher(), edit_provider(),
delete_producer(),
list_all_metadata()

3.​Design API

Endpoint Method Description

/api/customers/register/ POST Register a new


customer

/api/customers/login/ POST Login endpoint for


customers

/api/items/ GET/POST Retrieve or add base


item

/api/books/ POST Add book linked to item


and publisher

/api/devices/ POST Add electronic device


with provider and
producer

13
/api/cart/ GET/POST/DELETE Cart operations

/api/orders/ GET/POST Place or retrieve orders

/api/payments/ POST Initiate payment

/api/bank/validate/ POST Validate payment


(mocked bank service)

/api/shipping/track/<id>/ GET Track shipping status

/api/staff/login/ POST Staff login

/api/admin/providers/ GET/POST Manage provider


records (admin only)

/api/admin/publishers/ GET/POST Manage publisher


records (admin only)

/api/admin/producers/ GET/POST Manage producer


records (admin only)

4.​Conclusion
The design phase of this e-commerce system has demonstrated a clear and
effective application of microservices architecture using Django. Each service
has been independently modeled, structured, and connected to promote high
cohesion, low coupling, and domain-driven design, which are fundamental
principles of modern software engineering.​

Microservices-Centric Architecture
The system has been decomposed into six core microservices: Customer,
Item,
Cart, Order, Payment, and Shipping. Each microservice is independently
responsible for a specific set of business capabilities and maintains its own
models, database schema, and logic. This separation allows for:
• Independent development and deployment of services.
• Improved scalability, as each service can be scaled horizontally based on
its specific demand.
• Fault isolation, meaning failure in one service (e.g., Shipping) does not
directly crash the others.
• Database autonomy, enabling optimized data storage technologies (e.g.,

14
using MongoDB for flexible item catalog and PostgreSQL for transaction
heavy modules).

Object-Oriented and Domain-Aligned Design


The class diagrams outlined in Section 2.2 reflect a rich, domain-driven
structure within each microservice. Core business entities such as Customer,
Item, CartItem, Order, and Payment encapsulate the relevant attributes and
operations, keeping the business logic close to the data. This promotes:
• Clear responsibilities within classes, reducing complexity.
• Encapsulation of business rules via class methods like applyCoupon(),
trackShipment(), and processPayment().
• Entity relationships (e.g., one-to-many between Orders and OrderItems)
that reflect real-world business processes.

RESTful API Design for Loose Coupling


Section 2.3 detailed a well-structured REST API layer for each service. The
use
of HTTP methods (GET, POST, PUT, DELETE) aligned with CRUD operations
ensures consistency and simplicity in how clients (e.g., frontend, mobile apps)
interact with the backend.
These APIs enable:
• Asynchronous communication between services, allowing them to
function independently.
• Front-end flexibility, as APIs can be consumed by various platforms
(web, mobile, admin dashboard).
• Future integrations with third-party tools, payment gateways, and
machine learning services.

Scalable, Maintainable, and Future-Ready


By embracing microservices and API-first design, this system is:
• Highly scalable: Individual services can be replicated or containerized
(e.g., via Docker) without impacting the rest of the system.
• Easier to maintain: Each service can be updated, refactored, or
redeployed independently.
• Ready for innovation: New services (e.g., Recommendation Engine,
Loyalty System) can be added without altering the core system.

15
16
17
18
19
20
21
22
23
24
Chapter 3 : AI In E-Commerce
1.​Application of Deep Learning in E-commerce
Deep learning is transforming e-commerce by automating personalization,
improving search, optimizing logistics, and enhancing user experience. Key
applications include:

🔹 Product Recommendation
Using customer behavior history, embedding-based models (e.g., Word2Vec
for product sequences) can recommend relevant items.

Deep neural networks such as DeepFM or Wide & Deep models can capture
high-order feature interactions.

🔹 Visual Search & Image Tagging

25
Convolutional Neural Networks (CNNs) can be used to analyze product
images and group similar-looking items.

Enables "search by image" and automated tagging of product features (color,


type, brand).

🔹 Dynamic Pricing
Recurrent Neural Networks (RNNs) or Transformer-based models forecast
demand, allowing for optimized dynamic pricing based on trends and
competitor activity.

🔹 Customer Support with Chatbots


Sequence-to-sequence models and transformer architectures (like BERT,
GPT) are used for natural-language understanding in support chatbots.

2.​Sentiment Analysis
Sentiment analysis extracts user opinions from product reviews or customer
support interactions.

🔹 Goal:
Classify a review or comment as positive, neutral, or negative.

🔹 Approaches:
Traditional ML:
Logistic Regression, Naive Bayes with Bag-of-Words or TF-IDF

Deep Learning:
LSTM, GRU with word embeddings (Word2Vec, GloVe)
Transformer Models (Recommended):
BERT, RoBERTa, DistilBERT — high accuracy, context-aware

🔹 Pipeline:
Data Preprocessing:
Remove stopwords, lowercase, punctuation, emojis

Tokenization:
Using HuggingFace Tokenizer
Model Input Formatting:
Add [CLS] token for BERT

26
Fine-tuning:
Use pretrained BERT → Fine-tune on labeled e-commerce reviews

Output:

3.​Applying Sentiment Analysis for Recommendation ​


Integrating sentiment analysis enhances
personalization and product quality feedback in
recommendations.

Use Cases:
-​ Review-aware Recommendation: Models like DeepCoNN and NARRE
combine user-item interaction with review embeddings.
-​ Sentiment Filtering: Boost or reduce visibility of products based on
recent sentiment trends.
-​ Cold Start Enhancement: Use textual sentiment to compensate for

🔹
limited purchase data.
Workflow:​
- Collect and clean review text
- Use a fine-tuned BERT model for sentiment classification
- Generate a sentiment score for each product-user pair
- Combine with purchase history in hybrid recommendation engines

4.​Deployment
To bring these AI features into production, several deployment strategies can
be used:

Tools & Frameworks:


Model Serving: TensorFlow Serving, TorchServe, FastAPI for custom Python
models
Dockerization: Containerizing models and inference services

27
Message Queues: RabbitMQ or Kafka for real-time sentiment analysis on
reviews
Monitoring: Prometheus + Grafana for model inference performance and
uptime

Architecture Integration:
AI services can be treated as microservices, callable from Django apps
REST API endpoints like /api/reviews/sentiment/ can classify incoming text
Recommendation services can run periodically or respond to user sessions
dynamically

Step 1: Model Development and Training
Before deployment, train your sentiment classification model (e.g., fine-tune
BERT) using labeled customer review data.
Example Workflow:
Data Preparation: Clean and label your customer review dataset.
Model Selection: Choose a model like DistilBERT (lightweight but powerful).
Fine-tuning: Train on sentiment labels (positive, negative, neutral).
Save the model using transformers and torch.save() or
model.save_pretrained().

Step 2: Build a FastAPI Inference Service


Why FastAPI?
Fast, lightweight, async-ready
Perfect for serving ML models

Step 4: Connect AI Microservice with Django


In Django, create a utility to call the AI microservice:

Step 5: Queue Real-Time Analysis (Optional but Scalable)


For real-time sentiment processing (async), use:
Tools:
RabbitMQ / Kafka: For async review processing
Celery: Background tasks in Django

Step 6: Monitor & Scale the AI Service


Use Prometheus + Grafana for monitoring:
Metrics to monitor:

28
Request throughput
Latency (API response time)
Error rates
GPU/CPU usage
Add Prometheus client to your FastAPI:
bash

Step 7: Periodic Batch Updates (Recommendation)


Run a batch job to update product recommendation scores using
sentiment-weighted logic.
Use a scheduled job:
Via cron
Django management command
Celery beat task

5.​Conclusion
The integration of AI and deep learning into e-commerce systems brings a
new level of intelligence, automation, and personalization. From
understanding customer emotions through sentiment analysis to delivering
smarter product recommendations, AI enables a scalable, adaptive, and
customer-centric shopping experience.

Future directions include:


Real-time adaptive UX based on sentiment
Emotion-aware voice agents
Fully automated inventory and pricing control based on AI insights

29
Chapter 4 Implementation and deployment

30
Models.py

31
32
33
34
35
36
Serializers.py

37
38
views.py

39
40
41
42
Urls.py

43
44
Templates

45
46
47
48
49
50
Running

51
52
53
54
55

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy