About this guide

Status: supplementary. This guide is staged material provided for study and practice.

Source of course structure: The 2025 Tribhuvan University course structure lists BCA404-II E-Commerce, Semester 7, 3 credits. The official TU document confirms the course identity but has no detailed micro-syllabus or numbered unit outline. This guide is built from general e-commerce knowledge and pedagogical practice appropriate for a Bachelor of Computer Application semester-7 E-Commerce course. It is not the official TU micro-syllabus.

Not official: This guide is not the official Tribhuvan University micro-syllabus. The official TU 2025 record publishes no numbered unit outline for this course. All topic titles, explanations, worked examples, labs, and review questions are original BCA Nepal study material created to ground the listed themes. Nothing here is copied from the TU source beyond the course code, semester, credit count, and subject name derived from the structure listing.

Teaching material: All explanations, labs, solved examples, diagrams, and practice exercises below are original BCA Nepal material designed for classroom and self-study use. They are intended to support learning the E-Commerce topics appropriate for a semester-7 BCA course.

Privacy and legal context: This guide discusses payment systems, data handling, and security practices. All examples are educational. Verify current legal and regulatory requirements before applying them to a production system.


Introduction

E-Commerce transforms how businesses and consumers exchange value. This guide covers the foundational through advanced topics expected in a semester-7 BCA E-Commerce course, organized thematically — not into numbered units — so you can study topics in the order that best suits your learning path. The material is grounded in general e-commerce principles and Nepal-specific context where relevant. Because the official TU 2025 record publishes no numbered unit outline, all explanations, labs, and review questions are original BCA Nepal study material.


E-Commerce Models

E-commerce is classified by the nature of the participants and the direction of goods, services, or money.

  • B2C (Business-to-Consumer): Business sells to end consumers. Example: an online clothing retailer. This is the most common e-commerce model.
  • B2B (Business-to-Business): Business sells to other businesses. Example: wholesale software licences, industrial component suppliers. Often involves larger order volumes, longer sales cycles, and negotiated pricing.
  • C2C (Consumer-to-Consumer): Consumer sells to other consumers. Example: eBay, Craigslist, local peer-to-peer marketplaces. Platforms provide the marketplace, payment processing, and buyer-seller protection.
  • C2B (Consumer-to-Business): Consumer sells services or products to businesses. Example: a freelance graphic designer offering services on Upwork, a photographer licensing images to a corporation. Growing with the gig economy.
  • B2G (Business-to-Government): Business provides goods or services to government entities. Example: IT tender responses, office supply contracts.
  • C2G (Consumer-to-Government): Consumer pays fees or files returns directly with government. Example: online passport renewal, tax filing portals.

Nepal context: Nepali businesses use marketplace platforms, social channels, and standalone storefronts. The channel mix depends on audience, logistics, payment options, and trust.


Platform Architecture

A typical e-commerce platform comprises several layered components:

  • Frontend (client-facing): The user interface — website or mobile app — built with HTML/CSS/JS, React, Vue, or native mobile frameworks. Responsible for product browsing, cart management, checkout UI, and user accounts.
  • Backend (server-side): Business logic, order processing, inventory management, user authentication, and API services. Common stacks: Node.js/Express, Python/Django/Flask, Ruby on Rails, PHP/Laravel, or Java/Spring. Exposes REST or GraphQL APIs.
  • Database: Stores product catalogs, user accounts, order histories, payment records, and session data. Relational databases (PostgreSQL, MySQL) for structured data; NoSQL (MongoDB) for flexible product attributes or session storage.
  • Payment gateway integration: Connects the platform to payment processors, banks, and wallet providers. Handles transaction initiation, authorization, capture, refunds, and webhook notifications.
  • Order management system (OMS): Tracks orders from cart to delivery, including status updates (placed, confirmed, processing, shipped, delivered, cancelled), inventory allocation, and customer notifications.
  • Inventory management: Real-time stock tracking, low-stock alerts, product variant management (size, colour, SKU), and sync across multiple sales channels.
  • Content management: Product descriptions, images, categories, and promotional content. Often integrated with the product catalog via a CMS or headless commerce setup.
  • Analytics and reporting: Traffic analysis, conversion funnel tracking, average order value, customer lifetime value, cart abandonment rate, and product performance dashboards.
  • Optional modules: Search (ElasticSearch/OpenSearch), recommendation engines, email/SMS marketing, review systems, affiliate tracking, and multi-store/locale management.

Nepal context: A Nepali storefront may use a hosted commerce service or a custom application. Local payment and delivery options vary by provider and region, so confirm current APIs and service coverage during project planning.


Catalog and Cart Flows

Product Catalog

  • Listing page: Displays products with images, titles, prices, short descriptions, and quick-action buttons (Add to cart, Wishlist).
  • Product detail page (PDP): Full product information — long description, specifications, images/gallery, availability status, reviews, related products, and size/colour selectors.
  • Search and filtering: Keyword search, category navigation, price range, brand, colour, size, and rating filters. Backend search may use exact-match, fuzzy-search, or full-text search (ElasticSearch).
  • Pagination/infinite scroll: Manages large catalogs across multiple pages or continuous loading.

Shopping Cart

  • Cart persistence: Cart state stored in browser localStorage, cookies, or server-side session, tied to a user account for cross-device recovery.
  • Cart operations: Add item (with quantity and options), update quantity, remove item, apply discount code, save for later.
  • Cart summary: Shows subtotal, taxes, shipping cost, discount amount, and total. Recalculates when cart changes.
  • Cart abandonment: Triggers follow-up emails, retargeting ads, or discount incentives after a configurable timeout (often 24–48 hours).
  • Guest checkout vs. account login: Guest checkout allows purchase without account creation; account login enables saved addresses, order history, and loyalty benefits.

Order Flow

  1. User browses and selects products → adds to cart.
  2. User proceeds to checkout → reviews cart, selects shipping address, chooses shipping method.
  3. User enters payment details or selects saved payment method → payment gateway authorization.
  4. Payment authorized → order status moves to "confirmed" or "processing."
  5. Order fulfilled → items picked, packed, shipped; tracking number generated; customer notified.
  6. Delivery confirmed → order status moves to "delivered"; optional review/request feedback.
  7. If payment fails → order marked "payment pending"; customer notified to retry; cart may be held for a limited time.
  8. If stock becomes unavailable → order line item backordered or cancelled; customer notified; refund processed if already charged.

Nepal context: Merchants may offer cash-on-delivery, wallet payments, bank transfers, or cards. Availability and customer preference vary by merchant, location, and provider.


Payments and Nepal Context

Payment Methods

  • Credit/debit cards (Visa, MasterCard, American Express): Global standard; requires PCI DSS compliance. In Nepal, card issuance is limited to select banks; many users rely on family cards or corporate cards.
  • E-wallets: Digital wallets that store value or link to bank accounts. Wallet providers may support online checkout, transfers, and QR payments. Check each provider's current features and availability.
  • Cash-on-delivery (COD): Customer pays cash to the delivery person upon receipt. Common in Nepal for first-time online shoppers or low-value orders. Adds logistics cost and risk of non-payment/non-delivery.
  • Bank transfer / direct deposit: Customer initiates a bank transfer from their account to the merchant's account. Requires merchant to share account details; reconciliation can be manual.
  • Cash pickup / voucher codes: Customer receives a voucher code or pickup location after online payment; physical cash exchanged at a partner outlet. Used by some Nepali platforms as a bridge for unbanked customers.
  • Buy now, pay later (BNPL): Installment plans through a third-party provider. Availability depends on market, merchant, and provider.
  • Mobile payment: Payments through a mobile banking or wallet app, including QR-based checkout where supported.

Nepal-Specific Payment Landscape

  • Provider mix: Wallets, bank apps, QR systems, and card schemes can support checkout. Provider names, features, and coverage change; check current documentation before integration.
  • Design constraints: Account access, connectivity, delivery reach, fraud awareness, and customer preference can affect payment choice.

Payment Gateway Integration (Technical Overview)

  • Provider API: Merchant integrates with a payment gateway (Stripe, PayPal, local gateway like eSewa/Khalti SDK). The gateway mediates between the merchant and the payment method network (card network, e-wallet API, bank API).
  • Flow: Customer enters payment details → frontend sends payment token/request to gateway → gateway communicates with acquiring bank/card network/e-wallet → authorization response returned → merchant fulfills order if authorized → settlement (funds transferred to merchant) after settlement period (often T+1 or T+2 days).
  • Webhooks: Gateway sends event notifications (payment.success, payment.failed, payment.refunded) to merchant's server for order status updates.
  • PCI DSS: Payment Card Industry Data Security Standard requirements for any system that stores, processes, or transmits cardholder data. Most merchants use gateway-hosted checkout (redirect to payment page or iframe) to reduce PCI scope.

Privacy, Security, and Fraud

Privacy Principles

  • Data minimization: Collect only the data needed for the transaction and service. Avoid collecting unnecessary personal details.
  • Consent: Clear, informed consent before collecting personal data; easy opt-out or withdrawal.
  • Purpose limitation: Use data only for the stated purpose; do not repurpose for unrelated marketing or analytics without additional consent.
  • Security safeguards: Technical and organizational measures to protect data from unauthorized access, modification, or disclosure.
  • Transparency: Privacy policy clearly states what data is collected, how it is used, who it is shared with, and how long it is retained.
  • User rights: Access, correction, and deletion rights for users regarding their personal data.

Security Controls

  • Transport security: TLS/HTTPS for all web traffic; HTTP Strict Transport Security (HSTS) to force HTTPS; certificate management and renewal.
  • Authentication: Strong customer authentication (SCA) per PSD2 for EU, or MFA (multi-factor authentication) for customer accounts. Avoid password-only login for sensitive accounts.
  • Session management: Secure, HttpOnly, SameSite cookies; session regeneration after login; idle and absolute timeout; server-side session invalidation at logout.
  • Input validation and output encoding: Prevent injection (SQL, OS, command) and cross-site scripting (XSS) at the point of data entry and rendering.
  • Error handling: Generic error messages to users; detailed errors logged only on server; no stack traces or sensitive data exposed to clients.
  • Dependency management: Regular dependency updates; vulnerability scanning (Snyk, Dependabot); avoid deprecated or unmaintained libraries.
  • Secret management: Never hardcode API keys, passwords, or certificates in source code or environment checkins. Use secrets managers (Vault, AWS Secrets Manager, Cloudflare Secrets) or environment variables with restricted access.

Common E-Commerce Fraud Types

  • Card-not-present (CNP) fraud: Stolen card details used for online purchases without the physical card. The most common e-commerce fraud type.
  • Identity theft: Fraudster uses stolen personal information (name, address, phone) to open accounts or make purchases.
  • Account takeover (ATO): Fraudster gains access to a legitimate customer's account (via credential stuffing, phishing, or data breach) and makes unauthorized purchases or changes shipping addresses.
  • Friendly fraud (chargeback abuse): Customer makes a legitimate purchase but later disputes the charge with their bank, claiming it was unrecognized or unauthorized — to keep the product and get a refund.
  • Refund fraud: Customer returns empty packaging or a filled-to-empty box; or requests a refund for a non-delivered item while keeping the product.
  • Phishing and social engineering: Fraudulent emails, messages, or calls tricking users into revealing payment credentials or login details.
  • Interception fraud: Order shipped to a legitimate address, but intercepted by a third party before the recipient receives it.
  • Triangulation fraud: Fraudster sets up a seemingly legitimate store, collects customer payment details, then purchases the item from a real retailer using stolen card data, shipping to the customer who unknowingly participated.

Fraud Prevention Measures

  • Address verification service (AVS): Matches billing address provided by customer with the address on file at the card issuer.
  • Card verification value (CVV/CVC): Three- or four-digit code on the card; not stored per PCI DSS, but requested at checkout.
  • Velocity checks: Limit number of orders per customer, per card, per IP, per time window to detect bulk fraud.
  • Device fingerprinting: Identify devices by browser/OS characteristics, installed fonts, screen resolution, etc., to detect suspicious or repeat devices.
  • GeoIP and IP reputation: Cross-reference customer IP location with billing/shipping address; flag high-risk countries or known malicious IPs.
  • Machine learning models: Train on historical transaction data to score risk (0–1) in real time; factors include velocity, geolocation, device fingerprint, order value, and customer history.
  • 3D Secure (3DS): Additional authentication layer (OTP sent to registered mobile, bank app approval) for card-not-present transactions. Reduces liability shift to issuer in many regions.
  • Risk scoring and rules engine: Configurable rules (e.g., "order > $500 from high-risk country → additional verification") combined with ML scores.
  • Manual review queue: High-risk orders flagged for manual verification (contact customer, verify identity, check shipping address consistency) before fulfillment.

Nepal context: Card-not-present fraud is an emerging concern as e-commerce grows. Many Nepali users rely on e-wallets (eSewa, Khalti) which have their own fraud monitoring. COD reduces CNP fraud but introduces delivery non-payment risk. Platforms should implement basic risk scoring, address verification where available, and educate users on phishing and OTP safety. Merchants should follow provider security instructions and verify current official requirements.


Fulfillment and Logistics

Order Fulfillment Process

  1. Order received → inventory reserved, order status updated to "confirmed" or "processing."
  2. Pick: Warehouse staff locate the ordered item(s) using order slip or WMS (warehouse management system) scan.
  3. Pack: Item(s) packed with appropriate packaging, included documentation (packing slip, invoice, return label), and protective materials.
  4. Ship: Courier or logistics provider picks up package; shipping label generated; tracking number recorded; order status updated to "shipped."
  5. Delivery: Courier delivers to customer address; delivery attempted, failed, or completed; status updated to "delivered."
  6. Post-delivery: Customer confirms delivery; optional review/rating; if issues (damaged, wrong item), return or exchange initiated.

Inventory Management

  • Real-time stock tracking: Each sale decrements inventory count; low-stock alerts trigger reorder.
  • Backorder: If item out of stock, order can be placed on backorder; customer notified of expected shipping date.
  • Pre-order: Customers can order upcoming products; payment may be partial or full; inventory allocated when available.
  • Omnichannel sync: Inventory synchronized across online store, physical shop(s), and marketplace listings (prevents overselling).

Last-Mile Delivery

  • Courier partners: Local (Gauradhan, UPS, FedEx, DHL, regional post) and regional delivery services.
  • Delivery options: Standard (3–7 days), express (1–3 days), same-day (within metropolitan area), pickup at locker/partner store.
  • Tracking: Customers receive tracking number and can track shipment status online or via SMS.
  • Delivery confirmation: Signature, photo, or mobile OTP confirmation at delivery.
  • Reverse logistics: Return process — customer initiates return, receives return label/label code, ships item back, inspection, refund or exchange processed.

Nepal context: Last-mile delivery in Nepal varies significantly between Kathmandu Valley (better infrastructure, more courier options) and other districts. COD is prevalent, and many customers prefer receiving before paying. E-wallet payments and bank transfers are growing. Reverse logistics (returns) is underdeveloped; many platforms have store-credit-only return policies or require customers to ship back at their own cost. Partner couriers include Gauradhan, Classic Couriers, and local post offices. Inventory management for small Nepali e-commerce often uses spreadsheets or basic WooCommerce stock tracking rather than enterprise WMS.


Analytics and Metrics

Core E-Commerce Metrics

  • Traffic: Number of visitors, unique visitors, page views, sessions, channel breakdown (organic search, paid search, social, direct, referral, email).
  • Conversion rate: Percentage of visitors who complete a desired action (typically purchase = orders / sessions × 100). Typical e-commerce conversion: 1–3% depending on industry.
  • Average order value (AOV): Average total spent per order = revenue / number of orders.
  • Customer lifetime value (CLV or LTV): Predicted net profit from the entire future relationship with a customer; depends on AOV, purchase frequency, and customer lifespan.
  • Cart abandonment rate: Percentage of carts where checkout was started but not completed = (cart initiated – purchases) / cart initiated × 100. Typical: 60–80%.
  • Traffic-to-order conversion: Overall store conversion from visit to purchase.
  • Traffic sources effectiveness: Return on ad spend (ROAS) for paid campaigns; organic search visibility and click-through rates.

Funnel Analysis

  • Browsing → product view: Are product pages engaging? Do images, descriptions, and prices convince visitors to view details?
  • Product view → cart add: Are product pages convincing enough to add to cart? Are pricing, shipping cost, and trust signals clear?
  • Cart → checkout start: Is the cart summary clear? Are shipping options and prices transparent? Is guest checkout available?
  • Checkout → payment authorization: Are payment options relevant? Is the checkout form frictionless? Are unexpected costs (shipping, taxes) disclosed late?
  • Payment → order confirmed: Is the payment gateway reliable? Are declines handled gracefully with clear next steps?

Tools

  • Google Analytics 4 (GA4): Traffic, funnel exploration, conversion tracking, audience segmentation.
  • Heatmaps & session recording: Hotjar, Microsoft Clarity — visualize where users click, scroll, and drop off.
  • E-commerce platform analytics: Built-in dashboards (WooCommerce, Shopify, Daraz seller portal) — orders, AOV, conversion, best-selling products.
  • Marketing analytics: Facebook Ads Manager, Google Ads, Meta Business Suite — campaign performance, ROAS, audience insights.
  • Custom dashboards: Combine platform data, advertising data, and warehouse data (Looker, Tableau, Power BI) for holistic business metrics.

Nepal context: Many Nepali e-commerce SMEs start with Facebook Page + WhatsApp ordering, using simple counters for stock and manual records for orders. As they grow, they adopt WooCommerce + GA4 or Shopify. Free or low-cost analytics (Google Search Console, Meta Insights) are common. Advanced funnel analysis and cohort segmentation are less common but growing with digital maturity.


Strategy

E-Commerce Strategy Framework

  • Value proposition: What unique value does this store offer? (Price, selection, convenience, niche expertise, customer service.) Must be clear within seconds of landing on the site.
  • Target market: Who are the customers? Demographics, geography, behaviour, needs. Segment for personalized marketing and product recommendations.
  • Product strategy: What to sell, how to source (own brand, wholesale, dropship, marketplace), pricing strategy (cost-plus, competitive, value-based), and inventory management.
  • Channel strategy: Own website (owned platform), marketplace (Daraz, Amazon), social commerce (Facebook, Instagram), or omnichannel blend. Each has different fees, audience, and control trade-offs.
  • Marketing strategy: Customer acquisition (SEO, paid ads, social media, influencer, affiliate), retention (email/SMS, loyalty program, personalization), and reactivation (win-back campaigns, discounts for lapsed customers).
  • Operations strategy: Order fulfillment speed and quality, customer service model (live chat, email, phone), return policy, and scalability for traffic and order volume spikes.
  • Technology strategy: Platform choice (SaaS like Shopify, self-hosted like WooCommerce, custom-built), integration ecosystem (ERP, CRM, payment gateways, shipping providers), and future extensibility.

Competitive Analysis

  • Identify direct competitors (same products, same geography) and indirect competitors (different products, same target need).
  • Compare on: product range, pricing, shipping speed/cost, return policy, user experience, trust signals, payment options, customer service, and reviews.
  • SWOT analysis (Strengths, Weaknesses, Opportunities, Threats) for your store vs. key competitors.
  • Use findings to differentiate (e.g., better return policy, faster shipping for Kathmandu, niche product selection, superior customer service).

Growth Stages

  • Launch: Focus on getting first customers, validating product-market-fit, collecting reviews, and building initial trust. Marketing may be lean (content, social, word-of-mouth).
  • Growth: Scale traffic and orders, optimize conversion funnel, introduce retention programs, expand product range, and invest in paid acquisition with measured ROAS.
  • Mature: Optimize operations, automate fulfillment and customer service, introduce advanced personalization, explore new channels or markets, and protect market share against new entrants.
  • Decline or pivot: Monitor metrics for sustained decline; consider product line refresh, market expansion, or business model pivot.

Nepal context: Many Nepali e-commerce ventures start as Facebook-based shops with minimal overhead, then migrate to WooCommerce or Shopify as volume grows. Differentiation often comes from local product selection (handicrafts, organic food, Nepali attire), faster COD trust-building, local language support, and reliable delivery in Kathmandu Valley. Competitive analysis should include both formal online stores and informal Facebook/Daraz sellers. Growth capital is often limited, so cash-flow-positive reinvestment is prioritized over burn-heavy scaling.


Case Study: A Nepalese E-Commerce Startup

Background

BizNepal Online (fictional composite) launched in 2023 as a B2C e-commerce store selling handcrafted Nepali products (passementerie, home décor, tea, and spices) through its own website and Daraz marketplace. Target market: Nepali diaspora and domestic customers seeking authentic Nepali gifts. Initial focus: Kathmandu Valley delivery with COD; e-wallet and card options for urban customers.

Challenges

  • Trust: First-time online shoppers skeptical of paying before delivery.
  • Logistics: Inconsistent courier service across districts; delivery delays; cash handling risk.
  • Payments: Limited card ownership; e-wallet adoption growing but not universal.
  • Visibility: Competing with established players (Daraz, Sastodeal) on marketplace search and advertising.
  • Returns: No standardized return process; customers reluctant to order without trying.

Strategies Implemented

  1. COD trust-building: 30-day exchange policy (store credit) for damaged/wrong items; clear "30-day exchange" messaging on product pages and checkout.
  2. E-wallet incentives: 5% discount for eSewa/Khalti payments; promoted at checkout and in abandoned-cart emails.
  3. Local SEO: Product descriptions and blog content in Nepali and English; "Nepali handicrafts" and "gift items Nepal" keyword targeting.
  4. Social proof: Customer photos and reviews displayed on product pages; Instagram integration showcasing real-user images.
  5. Limited COD fee: Small Rs. 50 COD fee (waived on orders > Rs. 2000) to offset cash-handling cost while keeping COD available.
  6. Partner with local couriers: Negotiated fixed rates with Gauradhan for Kathmandu; real-time tracking added to order page.
  7. Influencer collaboration: Micro-influencers (5K–20K followers) showcased products in Stories; trackable discount codes measured ROI.

Results (6 months post-launch)

  • 2,400 unique visitors, 68 orders, 2.8% conversion rate.
  • AOV: Rs. 3,200; 40% of orders paid via eSewa/Khalti; 60% COD.
  • 23% repeat purchase rate within 90 days (loyalty discount triggered re-order).
  • 12% cart abandonment recovery via email + 5% discount (abandoned-cart flow).
  • Positive customer feedback on product quality and customer service response time.

Key Takeaways

  • COD remains essential for Nepali first-time online shoppers; small COD fee offsets cost without deterring orders.
  • E-wallet incentives drive adoption and reduce COD logistics cost.
  • Local SEO and social proof are critical for trust and discovery in a competitive marketplace.
  • Influencer marketing with trackable codes can deliver measurable ROI even with micro-influencers.
  • A simple, clear return/exchange policy reduces purchase friction more than lenient but complex policies.

Lab with Worked Solution

Lab 1: Design a Product Catalog Schema

Objective: Design a relational database schema for a product catalog that supports multiple categories, product variants (size/colour), and basic search functionality.

Requirements:

  1. Tables: categories, products, product_variants, product_images.
  2. Each product belongs to one or more categories (many-to-many).
  3. Each product has one or more variants (e.g., size M/C, colour Red/Blue), each with SKU, price, and stock quantity.
  4. Each variant has one or more images with alt text and display order.
  5. Support querying: list all products in a category, list all variants for a product, find a variant by SKU.

Worked Solution — ER Diagram & SQL:

-- Categories table
CREATE TABLE categories (
    category_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(200) NOT NULL,
    slug VARCHAR(250) UNIQUE,
    parent_id INT,
    FOREIGN KEY (parent_id) REFERENCES categories(category_id)
);

-- Products table
CREATE TABLE products (
    product_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(250) NOT NULL,
    description TEXT,
    slug VARCHAR(250) UNIQUE,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Product-category link (many-to-many)
CREATE TABLE product_categories (
    product_id INT,
    category_id INT,
    PRIMARY KEY (product_id, category_id),
    FOREIGN KEY (product_id) REFERENCES products(product_id),
    FOREIGN KEY (category_id) REFERENCES categories(category_id)
);

-- Product variants (size/colour/SKU/price/stock)
CREATE TABLE product_variants (
    variant_id INT PRIMARY KEY AUTO_INCREMENT,
    product_id INT NOT NULL,
    sku VARCHAR(100) UNIQUE NOT NULL,
    title VARCHAR(200),
    price DECIMAL(10,2) NOT NULL,
    stock_quantity INT DEFAULT 0,
    is_active BOOLEAN DEFAULT TRUE,
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);
-- Example variant: title = "Red, Size M"

-- Product images
CREATE TABLE product_images (
    image_id INT PRIMARY KEY AUTO_INCREMENT,
    variant_id INT,
    product_id INT,
    url VARCHAR(500) NOT NULL,
    alt_text VARCHAR(250),
    display_order INT DEFAULT 0,
    is_primary BOOLEAN DEFAULT FALSE,
    FOREIGN KEY (variant_id) REFERENCES product_variants(variant_id),
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

-- Indexes for common queries
CREATE INDEX idx_product_categories_category ON product_categories(category_id);
CREATE INDEX idx_product_variants_sku ON product_variants(sku);
CREATE INDEX idx_product_images_primary ON product_images(product_id, is_primary DESC);

Query examples:

  • List all products in the "Tea" category:

    SELECT p.name, p.slug, v.sku, v.price, v.stock_quantity
    FROM products p
    JOIN product_categories pc ON p.product_id = pc.product_id
    JOIN product_variants v ON p.product_id = v.product_id
    JOIN categories c ON pc.category_id = c.category_id
    WHERE c.name = 'Tea' AND p.is_active = TRUE AND v.is_active = TRUE;
    
  • Find a variant by SKU:

    SELECT v.sku, v.price, v.stock_quantity, p.name AS product_name
    FROM product_variants v
    JOIN products p ON v.product_id = p.product_id
    WHERE v.sku = 'TEA-001-R-M';
    

Reflection question: How would you modify this schema to support product attributes beyond size/colour (e.g., weight, material, flavour)? Answer: Use an product_attributes EAV (entity-attribute-value) table or a NoSQL document store (MongoDB) where each product document can have flexible fields.


Lab 2: Calculate Cart Total with Taxes and Discounts

Objective: Given a cart with items, taxes, and a discount code, compute the final total.

Input data (example):

Item Quantity Unit Price
T-shirt (Red, M) 2 1200
Tea box (Orange Flavour) 1 800
  • Subtotal: sum of (quantity × unit price) for all items.
  • Tax rate: 13% (Nepal VAT on goods).
  • Discount code "WELCOME10": 10% off subtotal, minimum spend Rs. 1000, one-time use.
  • Shipping: Fixed Rs. 100 for Kathmandu; free shipping on subtotal > Rs. 2000.

Worked Solution:

  1. Subtotal: (2 × 1200) + (1 × 800) = 2400 + 800 = Rs. 3200
  2. Discount: Subtotal (3200) ≥ minimum spend (1000), so discount applies. 10% of 3200 = Rs. 320. Discounted subtotal = 3200 − 320 = Rs. 2880
  3. Shipping: Discounted subtotal (2880) > free-shipping threshold (2000), so shipping = Rs. 0
  4. Tax: Tax is applied to (subtotal − discount) before shipping in many systems. Tax = 13% × 2880 = Rs. 374.40. (Some systems tax subtotal before discount; clarify with business rules.)
  5. Total: Discounted subtotal + tax + shipping = 2880 + 374.40 + 0 = Rs. 3254.40

Alternative: tax-on-subtotal-before-discount

  • Tax = 13% × 3200 = Rs. 416
  • Total = 3200 − 320 (discount) + 416 (tax) + 0 (shipping) = Rs. 3296

Note: Tax treatment of discounts varies by jurisdiction. In Nepal, VAT is typically charged on the net amount after legitimate discounts; verify with a tax consultant for production use.


Lab 3: Identify Fraud Indicators in a Transaction

Objective: Given a set of transaction features, compute a simple risk score and identify red flags.

Transaction features:

Feature Value
Order amount Rs. 15,000
Customer IP country Nigeria
Billing country Nepal
Shipping country Nigeria
Email domain free email (Gmail)
Order velocity 3 orders in the last 30 minutes from same IP
Customer account age New (registered 10 minutes ago)
Shipping address matches billing No (different city)
Payment method Card-not-present (entered manually)

Worked Solution — Risk Scoring:

Assign 1 point per red flag, 2 points for high-risk indicators:

  1. IP country ≠ billing country → 1 point
  2. Shipping country ≠ billing country → 1 point (here, shipping = Nigeria, billing = Nepal → mismatch)
  3. Email domain is free → 1 point
  4. Order velocity > 1 in 30 min → 2 points (3 orders in 30 min)
  5. New account (registered < 24 hours) → 1 point
  6. Payment method CNP without 3DS → 1 point
  7. Shipping address differs from billing → 1 point (already counted in #2, do not double-count)

Total risk score: 7 points (out of a possible scale: low < 3, medium 3–6, high > 6).

Red flags identified:

  • IP country (Nigeria) differs from billing (Nepal) — possible stolen card used from another country.
  • Shipping to Nigeria while billing in Nepal — classic interception or reshipping fraud.
  • Free email domain + new account — low identity verification.
  • High velocity in short time — card-testing or bulk fraud.
  • CNP without 3DS — no additional authentication.

Mitigation actions:

  • Flag order for manual review before fulfillment.
  • Contact customer to verify identity (email the on-file address, call registered phone).
  • Require 3DS/OTP verification before proceeding.
  • If customer cannot verify, cancel order and refund if payment captured.
  • Add to blocklist if confirmed fraud; monitor for repeat patterns.

Lab 4: Compare Two Payment Scenarios

Scenario A: Customer pays Rs. 5,000 via eSewa wallet.

Scenario B: Customer pays Rs. 5,000 with Visa card, 3DS OTP verification.

Compare on:

Aspect Scenario A (eSewa) Scenario B (Visa 3DS)
Authentication Wallet app OTP or biometric (device-bound) Bank-issued OTP on registered mobile; SMS or app-based
Liability eSewa/issuer per e-wallet rules Liability shift to issuer if 3DS successful; merchant protected if decline
Transaction speed Instant (wallet balance or linked bank) Seconds additional for OTP entry
Fee to merchant eSewa merchant rate (e.g., 2%) Card gateway rate (e.g., 2.5%) + possible 3DS fee
Customer friction Low (already logged into wallet) Medium (OTP entry, may switch apps)
Reversibility eSewa refund policy; wallet-to-wallet Card chargeback possible within dispute window (typically 120 days)
Nepal prevalence High (growing rapidly) Moderate (card ownership lower)

Key takeaway: Both methods are valid; choice depends on merchant's customer profile, risk tolerance, and fee structure. Offering multiple payment methods maximizes conversion.


Review Questions with Answers

Question 1

Name and briefly describe three e-commerce models besides B2C.

Answer:

  • B2B (Business-to-Business): Business sells to other businesses. Example: wholesale software licences. Typically involves larger order volumes, longer sales cycles, and negotiated pricing.
  • C2C (Consumer-to-Consumer): Consumer sells to other consumers via a platform. Example: eBay, Facebook Groups. The platform provides marketplace, payment processing, and buyer-seller protection.
  • C2B (Consumer-to-Business): Consumer sells services or products to businesses. Example: a freelance designer on Upwork, a photographer licensing images. Growing with the gig economy.

Question 2

What are the key components of an e-commerce platform's architecture?

Answer: Frontend (website/app), backend (business logic, APIs), database (products, users, orders), payment gateway integration, order management system, inventory management, content management, and analytics/reporting. Optional: search, recommendation engine, marketing modules.

Question 3

Describe the typical order flow from cart to delivery.

Answer: User adds items to cart → proceeds to checkout → enters shipping and payment details → payment gateway authorizes → order status moves to "confirmed/processing" → items picked and packed → shipped with tracking number → delivered → customer confirms → order status moves to "delivered." If payment fails, order marked "payment pending"; if stock unavailable, item backordered or cancelled.

Question 4

What is card-not-present (CNP) fraud, and how does it differ from card-present fraud?

Answer: CNP fraud occurs when stolen card details are used for online purchases without the physical card being present. The cardholder may not discover the fraud until seeing the statement. Card-present fraud requires the physical card, PIN or signature, and typically involves counterfeit cards or lost/stolen cards used at POS terminals. CNP is the most common e-commerce fraud type because card details can be stolen without the physical card leaving the owner's possession.

Question 5

Name three fraud prevention measures and explain how each works.

Answer:

  • AVS (Address Verification Service): Matches the billing address provided by the customer with the address on file at the card issuer. A mismatch may indicate fraud.
  • CVV/CVC verification: Requests the three- or four-digit code on the card; not stored per PCI DSS, but proves the customer physically has the card at checkout.
  • Velocity checks: Limits the number of orders per customer, card, or IP within a time window. Unusually high velocity (e.g., 10 orders in 1 hour) triggers additional review or automatic decline.

Question 6

Why is TLS/HTTPS essential for e-commerce sites?

Answer: TLS/HTTPS encrypts all data transmitted between the customer's browser and the web server, protecting payment details, login credentials, and personal information from interception or tampering by third parties. It also enables HTTPS-only cookies (Secure flag), satisfies PCI DSS requirements, and is a trust signal to customers (padlock icon, "secure" label).

Question 7

What is the role of a payment gateway in an e-commerce transaction?

Answer: The payment gateway mediates between the e-commerce platform and the payment method network (card network, e-wallet API, bank API). It handles transaction initiation, authorization request and response, capture, refunds, and webhook notifications for order status updates. Most merchants use a gateway to reduce PCI DSS scope by redirecting customers to a hosted checkout page or using an iframe.

Question 8

What are three key metrics every e-commerce business should track?

Answer:

  • Conversion rate: Percentage of visitors who make a purchase (orders / sessions × 100).
  • Average order value (AOV): Average total spent per order (revenue / number of orders).
  • Cart abandonment rate: Percentage of carts where checkout was started but not completed ((cart initiated – purchases) / cart initiated × 100).

Question 9

Describe the difference between a "backorder" and a "pre-order."

Answer: A backorder is an order for an item currently out of stock; the customer is told the expected shipping date, and the item is fulfilled when inventory arrives. A pre-order is an order for a product not yet released; the customer orders in advance, often paying a partial amount upfront or the full amount, and receives the product on or after the release date.

Question 10

What should an e-commerce site do to comply with Nepal's privacy and consumer protection laws?

Answer:

  • Publish a clear privacy policy stating what data is collected, how it is used, who it is shared with, and retention periods.
  • Obtain informed consent before collecting personal data; provide easy opt-out.
  • Secure data with TLS, access controls, and regular backups.
  • Honor user rights: access, correction, and deletion of personal data.
  • Display clear return, refund, and exchange policies.
  • Use trusted payment gateways.
  • Do not store card CVV/CVC numbers; comply with PCI DSS if handling card data.
  • Provide accurate product descriptions, pricing, and shipping information to avoid consumer disputes.

Glossary

Term Definition
Abandonment rate Percentage of shopping carts where the customer started checkout but did not complete the purchase.
AOV Average Order Value — the average total spent per order, calculated as revenue divided by number of orders.
B2B Business-to-Business — e-commerce model where businesses sell to other businesses.
B2C Business-to-Consumer — e-commerce model where businesses sell to end consumers.
C2C Consumer-to-Consumer — e-commerce model where consumers sell to other consumers via a platform.
C2B Consumer-to-Business — e-commerce model where consumers sell services or products to businesses.
Cart abandonment The situation where a shopper adds items to their online shopping cart but leaves the site without completing the purchase.
COD Cash-on-Delivery — a payment method where the customer pays for the goods at the time of delivery, not online.
Conversion rate The percentage of website visitors who complete a desired action (typically a purchase).
CNP Card-Not-Present — a card transaction where the physical card is not presented (e.g., online, telephone).
CVV/CVC Card Verification Value / Card Verification Code — the 3- or 4-digit code on a credit/debit card used to verify physical possession.
E-wallet A digital wallet that stores payment value or links to a bank account, enabling electronic transactions.
Fulfillment The end-to-end process of receiving, processing, and delivering customer orders.
Gateway A payment service that authorizes and processes card payments for e-commerce sites.
IMRAd Introduction, Methods, Results, and Discussion — standard structure for research papers and reports.
KYC Know Your Customer — verification process to confirm customer identity, often required for financial and e-wallet accounts.
Margin The difference between the cost of a product and its selling price; expressed as rupees or percentage.
Omnichannel A sales approach that provides a seamless customer experience across multiple channels (website, mobile app, physical store, marketplace).
PCI DSS Payment Card Industry Data Security Standard — a set of security standards designed to ensure that ALL companies that accept, process, store, or transmit credit card information maintain a secure environment.
ROI Return on Investment — the gain or loss generated relative to the amount of money invested.
SCA Strong Customer Authentication — a multi-factor authentication requirement under PSD2 for electronic payments in the EU.
SKU Stock Keeping Unit — a unique alphanumeric identifier for each distinct product variant (e.g., size, colour).
SSL/TLS Secure Sockets Layer / Transport Layer Security — cryptographic protocols that provide communications security over a computer network.
SLA Service Level Agreement — a commitment between service provider and customer defining expected service levels (e.g., delivery time, uptime).
SLA breach Failure to meet the terms of a service level agreement.
SWOT Strengths, Weaknesses, Opportunities, Threats — a strategic planning framework.
Tax Mandatory financial charge or levy imposed by a government body on products, services, or income. In Nepal, 13% VAT on most goods.
Token A non-sensitive placeholder used to represent sensitive data (e.g., payment token generated by a gateway instead of actual card number).
WMS Warehouse Management System — software for tracking inventory, orders, and shipping within a warehouse.

References and Further Reading