# E-Commerce Project Implementation Plan

## 1. Confirmed Technology Stack

```text
Backend Framework: Laravel 12
Backend Language: PHP 8.2+
Admin Interface: Laravel Blade Templates
Admin Styling: Bootstrap 5
Admin Interactivity: JavaScript, AJAX and jQuery where required
Data Tables: Yajra Laravel DataTables
Charts: Chart.js
API Authentication: Laravel Sanctum
Database: MySQL
Permissions: Spatie Laravel Permission
Activity Logs: Spatie Laravel Activity Log
API Format: RESTful JSON API
```

---

# 2. Project Overview

The E-commerce system will contain three main components:

1. Laravel 12 Backend and Admin Dashboard
2. CMS for Website Content Management
3. RESTful JSON API for the E-commerce Website

The Admin Dashboard will allow authorized administrators to manage:

- Administrators
- Roles and permissions
- Products
- Categories and subcategories
- Brands
- Units
- Product attributes
- Customers
- Customer addresses
- Shipping methods
- Orders
- Payments
- Returns and refunds
- Promotions
- Product reviews
- Website content
- Reports
- Website settings
- Activity logs

The public E-commerce website will connect to the Laravel backend through RESTful JSON APIs.

---

# 3. Project Objectives

The system must provide:

- Clean and modern Admin Dashboard
- Responsive Bootstrap 5 interface
- Secure administrator authentication
- Role-based access control
- Reusable Laravel Blade components
- AJAX-based CRUD operations
- Server-side Yajra DataTables
- Product management
- Customer management
- Shopping cart and checkout
- Fixed shipping-fee management
- Order and payment processing
- CMS content management
- RESTful API integration
- Dashboard statistics
- Chart.js reports
- Activity tracking
- Secure and maintainable Laravel architecture

---

# 4. Main System Components

## 4.1 Laravel Backend

The Laravel backend will handle:

- Business logic
- Database operations
- Authentication
- Authorization
- Product management
- Customer management
- Shopping-cart calculations
- Shipping-fee calculations
- Checkout processing
- Order processing
- Payment processing
- Return and refund processing
- CMS management
- Reporting
- API responses
- File management
- Image management
- Activity logging

## 4.2 Admin Dashboard

The Admin Dashboard will use:

- Laravel Blade layouts
- Laravel Blade components
- Laravel Blade partials
- Bootstrap 5
- JavaScript
- jQuery
- AJAX
- Yajra Laravel DataTables
- Chart.js
- SweetAlert2
- Select2
- Date-range picker
- Rich-text editor
- Image-upload components

## 4.3 CMS

The CMS will allow administrators to manage:

- Website pages
- Homepage sections
- Banners
- Sliders
- Menus
- Blogs
- FAQs
- Testimonials
- Contact information
- Footer content
- Newsletter subscribers
- Media files
- SEO content
- Website settings

## 4.4 RESTful API

The RESTful API will provide data and functionality to:

- Public E-commerce website
- Customer account area
- Future mobile application
- Payment gateways
- Approved third-party integrations

---

# 5. User Roles

## 5.1 Super Administrator

The Super Administrator can:

- Manage all administrators
- Manage roles and permissions
- Manage products
- Manage customers
- Manage shipping methods
- Manage orders
- Manage payments
- Manage CMS content
- Manage reports
- Manage system settings
- View activity logs

## 5.2 Administrator

The Administrator can:

- Manage products
- Manage categories
- Manage customers
- Manage shipping methods
- Manage orders
- Manage payments
- Manage CMS content
- View reports

## 5.3 Product Manager

The Product Manager can:

- Manage categories
- Manage brands
- Manage units
- Manage attributes
- Create products
- Edit products
- Manage product images
- Manage product prices
- Set product availability

## 5.4 Order Manager

The Order Manager can:

- View orders
- Create manual orders
- Confirm orders
- Update order statuses
- Update delivery statuses
- Print invoices
- Cancel orders
- Review return requests

## 5.5 Finance Manager

The Finance Manager can:

- View payments
- Verify payments
- Process refunds
- View payment reports
- View revenue reports

## 5.6 Content Manager

The Content Manager can:

- Manage CMS pages
- Manage banners
- Manage sliders
- Manage homepage sections
- Manage menus
- Manage blogs
- Manage FAQs
- Manage testimonials
- Manage SEO content

## 5.7 Customer Support

Customer Support can:

- View customers
- View customer orders
- Add order notes
- Review return requests
- Review refund history

---

# 6. Authentication Requirements

## 6.1 Administrator Authentication

The Admin Dashboard must support:

- Login
- Logout
- Forgot password
- Reset password
- Change password
- Remember me
- Login throttling
- Session management
- Account activation
- Account deactivation

## 6.2 Customer Authentication

The API must support:

- Customer registration
- Customer login
- Customer logout
- Forgot password
- Reset password
- Email verification
- Authenticated profile access

## 6.3 Security Controls

- Password hashing
- CSRF protection
- Session regeneration
- Login-attempt limitation
- Secure cookies
- HTTPS in production
- Sanctum token authentication
- API rate limiting

---

# 7. Roles and Permissions

Use:

```text
Package: Spatie Laravel Permission
```

Recommended permissions:

```text
dashboard.view

users.view
users.create
users.update
users.delete

roles.view
roles.create
roles.update
roles.delete

products.view
products.create
products.update
products.delete
products.export
products.update-availability

categories.view
categories.create
categories.update
categories.delete

brands.view
brands.create
brands.update
brands.delete

units.view
units.create
units.update
units.delete

attributes.view
attributes.create
attributes.update
attributes.delete

customers.view
customers.create
customers.update
customers.delete
customers.export

shipping-methods.view
shipping-methods.create
shipping-methods.update
shipping-methods.delete

orders.view
orders.create
orders.update
orders.cancel
orders.refund

payments.view
payments.verify
payments.refund

reviews.view
reviews.approve
reviews.reject
reviews.delete

cms.pages.view
cms.pages.create
cms.pages.update
cms.pages.delete
cms.pages.publish

reports.sales
reports.orders
reports.payments
reports.products
reports.customers

settings.view
settings.update

activity-logs.view
```

Every protected Admin Dashboard action must check the authenticated administrator’s permission.

---

# 8. Admin Dashboard

## 8.1 Summary Cards

Display:

- Total administrators
- Total customers
- Total products
- Total categories
- Total brands
- Total orders
- Pending orders
- Completed orders
- Cancelled orders
- Total revenue
- Total successful payments
- Total refunds
- In-stock products
- Out-of-stock products

## 8.2 Charts

Use Chart.js for:

- Daily sales
- Monthly revenue
- Yearly revenue
- Order-status distribution
- Payment-method distribution
- Customer-registration growth
- Best-selling products
- Sales by category
- Orders by shipping method

## 8.3 Dashboard Tables

Display:

- Recent orders
- Latest customers
- Recent payments
- Best-selling products
- Out-of-stock products
- Recent reviews
- Recent administrator activities

## 8.4 Dashboard Filters

Support:

- Today
- Yesterday
- This week
- This month
- Last month
- This year
- Custom date range

Dashboard statistics should load through AJAX where appropriate.

---

# 9. Administrator Management

## Required Features

- List administrators
- Create administrator
- View administrator
- Edit administrator
- Activate administrator
- Deactivate administrator
- Delete administrator
- Assign roles
- Assign permissions
- Reset password
- View login history
- View activity history
- Search administrators
- Filter administrators
- Export administrator list

## Administrator Fields

- Full name
- Email
- Phone number
- Profile image
- Password
- Role
- Status
- Email-verification status
- Last-login date
- Created date

---

# 10. Category and Subcategory Management

## Required Features

- List categories
- Create category
- View category
- Edit category
- Delete category
- Restore category
- Activate or deactivate category
- Set parent category
- Change display order
- Search categories
- Filter categories
- Export category list

## Category Fields

- Category name
- Slug
- Parent category
- Description
- Image
- Icon
- Display order
- Status

The category structure should support:

- Main category
- Subcategory
- Multiple category levels

---

# 11. Brand Management

## Required Features

- List brands
- Create brand
- View brand
- Edit brand
- Delete brand
- Restore brand
- Activate or deactivate brand
- Mark brand as featured
- Search brands
- Filter brands
- Export brand list

## Brand Fields

- Brand name
- Slug
- Logo
- Description
- Display order

---

# 12. Unit Management

## Required Features

- List units
- Create unit
- Edit unit
- Delete unit
- Activate or deactivate unit
- Search units

## Unit Fields

- Unit name
- Abbreviation
- Description
- Status

Examples:

- Piece
- Box
- Pack
- Set
- Kilogram
- Gram
- Liter
- Milliliter
- Meter

---

# 14. Product Management

## 14.1 Product DataTable

Use Yajra Laravel DataTables with:

- Server-side pagination
- Global search
- Sorting
- Category filter
- Brand filter
- Product-status filter
- Availability filter
- Featured-product filter
- Date-range filter
- Bulk status update
- Bulk deletion
- Export

## 14.2 Product Fields

Each product should include:

- Product name
- Slug
- Barcode
- Category
- Subcategory
- Brand
- Unit
- Short description
- Full description
- Sale price
- Tax information
- Availability status
- Minimum order quantity
- Maximum order quantity
- Product status
- Featured status
- New-arrival status
- Best-seller status
- Main image
- Product gallery
- Warranty information
- Return information
- SEO title
- SEO description
- SEO keywords

## 14.3 Product Availability

Only two availability values are required:

```text
in_stock
out_of_stock
```

Rules:

- An in-stock product can be added to the cart.
- An out-of-stock product cannot be added to the cart.
- Administrators manually update availability.
- Product APIs must return the current availability.
- Cart and checkout must validate the current availability.
- Availability must also be supported for product variants.

---

# 16. Product Media Management

The system should support:

- Main product image
- Multiple gallery images
- Image preview
- Image reordering
- Image deletion
- Alternative text
- Image compression
- Image resizing
- File-type validation
- File-size validation

Recommended formats:

- JPG
- JPEG
- PNG
- WebP

---

# 17. Product Import and Export

## Import Features

- Import products from Excel
- Import products from CSV
- Download import template
- Validate required columns
- Validate duplicate SKU
- Validate categories
- Validate brands
- Validate availability status
- Generate an import-error report

## Export Features

- Export all products
- Export filtered products
- Export product prices
- Export product availability
- Export product variants
- Export to Excel
- Export to CSV

---

# 18. Customer Management

## Required Features

- List customers
- Create customer
- View customer profile
- Edit customer
- Activate customer
- Suspend customer
- Delete customer
- Search customers
- Filter customers
- Export customer data

## Customer Fields

- Full name
- Email
- Phone number
- Gender
- Date of birth
- Profile image
- Customer group
- Status
- Email-verification status
- Phone-verification status
- Registration date
- Last login
- Total orders
- Total spending

## Customer Profile Information

- Personal information
- Saved addresses
- Order history
- Payment history
- Wishlist
- Reviews
- Return requests
- Refund history
- Activity history

---

# 19. Customer Address Management

Each customer may have multiple addresses.

## Address Fields

- Address label
- Recipient name
- Phone number
- Country
- Province
- City
- District
- Commune
- Village
- Street address
- Latitude
- Longitude
- Default shipping address
- Default billing address

---

# 20. Shopping Cart Requirements

## Cart Features

- Add product to cart
- Update quantity
- Remove product
- Clear cart
- Calculate subtotal
- Calculate product discount
- Calculate tax
- Calculate shipping fee
- Calculate grand total
- Validate product price
- Validate product status
- Validate availability
- Support authenticated-customer carts

## Cart Validation

The system must check:

- Product is active
- Product is in stock
- Product price is current
- Variant is active where applicable
- Variant is in stock where applicable
- Minimum quantity
- Maximum quantity

---

# 21. Shipping Method Management

Shipping methods will use CRUD operations and fixed fees.

## 21.1 Default Shipping Methods

Create the following records using a database seeder:

```text
Pick-up: $0.00
Delivery: $2.00
```

## 21.2 Shipping Method Fields

- Name
- Code
- Description
- Fixed fee
- Status
- Display order
- Created date
- Updated date

Example:

| Shipping Method | Code     | Fixed Fee | Status |
| --------------- | -------- | --------- | ------ |
| Pick-up         | pickup   | $0.00     | Active |
| Delivery        | delivery | $2.00     | Active |

## 21.3 Shipping Method CRUD

Administrators can:

- List shipping methods
- Create shipping method
- View shipping method
- Edit shipping method
- Delete shipping method
- Activate or deactivate method
- Change fixed fee
- Change display order
- Search methods
- Filter methods

## 21.4 Validation

- Name is required
- Code is required
- Code must be unique
- Fixed fee is required
- Fixed fee must be zero or greater
- Status must be valid
- Display order must be numeric

Recommended fee type:

```text
DECIMAL(10,2)
```

## 21.5 Shipping Fee Calculation

Formula:

```text
Grand Total = Subtotal + Tax + Shipping Fee - Product Discount
```

Pick-up example:

```text
Subtotal: $20.00
Shipping Method: Pick-up
Shipping Fee: $0.00
Grand Total: $20.00
```

Delivery example:

```text
Subtotal: $20.00
Shipping Method: Delivery
Shipping Fee: $2.00
Grand Total: $22.00
```

The backend must retrieve the fixed fee from the database.

The final fee must never be trusted from frontend input.

## 21.6 Shipping Snapshot

When an order is created, save:

- Shipping method ID
- Shipping method name
- Shipping method code
- Shipping fee

This ensures that previously created orders retain their original shipping fee.

---

# 22. Checkout Requirements

## Checkout Process

1. Customer reviews the cart.
2. System validates all products.
3. Customer selects a shipping address.
4. Customer selects a billing address.
5. Customer selects a shipping method.
6. Customer selects a payment method.
7. System retrieves the fixed shipping fee.
8. System calculates tax and the final total.
9. Customer accepts the terms and conditions.
10. Customer confirms the order.
11. System creates the order.
12. System creates the order items.
13. System saves the shipping-method snapshot.
14. System creates the payment transaction.
15. System clears the cart after successful completion.

## Checkout Features

- Customer checkout
- Address selection
- New-address creation
- Shipping-method selection
- Payment-method selection
- Terms and conditions acceptance
- Order summary
- Server-side total calculation
- Order confirmation

## Database Transaction

Checkout must use a MySQL database transaction.

When an operation fails:

- Do not save a partial order
- Do not save incomplete order items
- Do not create an incorrect payment transaction
- Do not clear the shopping cart

---

# 23. Order Management

## 23.1 Order Fields

- Order number
- Customer
- Customer email
- Customer phone
- Order date
- Order items
- Product quantity
- Product price
- Product discount
- Tax
- Shipping method
- Shipping fee
- Subtotal
- Grand total
- Payment method
- Payment status
- Order status
- Delivery status
- Billing address
- Shipping address
- Customer notes
- Administrator notes

## 23.2 Order Statuses

```text
pending
confirmed
ready_for_delivery
delivered
completed
cancelled
refunded
```

## 23.3 Delivery Statuses

```text
pending
ready_for_pickup
picked_up
delivered
```

## 23.4 Order Features

- List orders
- View order details
- Create manual order
- Confirm order
- Update order status
- Update payment status
- Update delivery status
- Add administrator notes
- Print invoice
- Download invoice
- Print packing slip
- Cancel order
- Approve return
- Reject return
- Process refund
- View order-status history

## 23.5 Order DataTable Filters

- Order number
- Customer
- Phone number
- Order status
- Payment status
- Payment method
- Shipping method
- Delivery status
- Date range
- Amount range

---

# 24. Payment Management

## 24.1 Payment Methods

The initial system may support:

- Cash on delivery
- ABA PayWay
- Bakong

## 24.2 Payment Fields

- Payment transaction number
- Order number
- Customer
- Payment method
- Amount
- Currency
- Payment status
- Payment proof
- Gateway transaction ID
- Gateway response
- Payment date
- Verification date
- Verified by
- Notes

## 24.3 Payment Statuses

```text
pending
paid
cancelled
refunded
```

## 24.4 Payment Features

- List payments
- View payment details
- Verify manual payment
- Reject payment proof
- Retry payment
- Process refund
- Download payment report
- View transaction history
- Prevent duplicate payments
- Store payment-gateway responses

---

# 25. Return and Refund Management

## Return Features

- Submit return request
- Select return reason
- Upload evidence
- Review return request
- Approve return
- Reject return
- Record returned product
- Process refund
- Close return request

## Return Fields

- Return number
- Order number
- Customer
- Product
- Quantity
- Return reason
- Description
- Evidence
- Product condition
- Return status
- Refund amount
- Refund method
- Administrator notes

## Return Statuses

```text
requested
approved
rejected
product_received
refund_processing
refunded
closed
```

---

# 26. Discount and Promotion Management

## Promotion Types

- Percentage discount
- Fixed-amount product discount
- Category discount
- Brand discount
- Flash sale
- Buy one get one
- Free shipping
- First-order discount

## Promotion Fields

- Promotion name
- Promotion type
- Discount value
- Start date
- End date
- Applicable products
- Applicable categories
- Applicable brands
- Minimum order value
- Maximum discount
- Status

---

# 27. Product Reviews and Ratings

## Required Features

- Customer rating
- Written review
- Verified-purchase status
- Review approval
- Review rejection
- Review reporting
- Average rating
- Rating distribution

## Review Statuses

```text
pending
approved
rejected
hidden
```

---

# 28. Wishlist Management

## Customer Features

- Add product to wishlist
- Remove product from wishlist
- View wishlist
- Move product to cart

## Admin Features

- View most-wishlisted products
- View wishlist statistics
- Use wishlist information in product reports

---

# 29. CMS Management

The CMS will be managed from the Laravel Blade Admin Dashboard.

## CMS Modules

- Page management
- Homepage sections
- Banners
- Sliders
- Menus
- Blogs
- FAQs
- Testimonials
- Contact information
- Footer management
- Newsletter subscribers
- Media library
- SEO management
- Website settings

---

# 30. CMS Page Management

## Standard Pages

- Home
- About Us
- Contact Us
- Privacy Policy
- Terms and Conditions
- Shipping Policy
- Return Policy
- Refund Policy
- Payment Policy

## Page Fields

- Title
- Slug
- Short description
- Full content
- Featured image
- Page template
- SEO title
- SEO description
- SEO keywords
- Publish status
- Publish date
- Display order

## Page Statuses

```text
draft
published
unpublished
archived
```

Use one rich-text editor:

- CKEditor
- TinyMCE
- Summernote

---

# 31. Homepage Section Management

Administrators can enable, disable and reorder homepage sections.

## Homepage Sections

- Hero slider
- Featured categories
- Featured products
- New arrivals
- Best-selling products
- Flash sales
- Featured brands
- Promotional banners
- Testimonials
- Latest blogs
- Newsletter
- Service benefits

## Section Fields

- Section name
- Title
- Subtitle
- Description
- Image
- Button text
- Button URL
- Background image
- Display order
- Status

---

# 32. Banner and Slider Management

## Fields

- Title
- Subtitle
- Desktop image
- Tablet image
- Mobile image
- Button text
- Button URL
- Position
- Start date
- End date
- Display order
- Open in new tab
- Status

## Positions

- Homepage hero
- Homepage middle
- Category page
- Product page
- Blog page
- Sidebar
- Footer

---

# 33. Menu Management

## Menu Types

- Header menu
- Footer menu
- Mobile menu
- Customer-account menu

## Menu Fields

- Title
- Parent menu
- Menu type
- URL
- Icon
- Display order
- Open in new tab
- Status

The system should support nested menus.

---

# 34. Blog Management

## Blog Features

- Blog categories
- Blog posts
- Blog tags
- Featured posts
- Related posts
- Draft status
- Published status
- Scheduled publication

## Blog Fields

- Title
- Slug
- Category
- Author
- Short description
- Full content
- Featured image
- Tags
- Publish date
- Featured status
- Status
- SEO title
- SEO description
- SEO keywords

---

# 35. FAQ Management

## Features

- Create FAQ category
- Create FAQ
- Edit FAQ
- Delete FAQ
- Reorder FAQs
- Mark FAQ as featured
- Activate or deactivate FAQ

## Fields

- Category
- Question
- Answer
- Display order
- Featured status
- Status

---

# 36. Testimonial Management

## Fields

- Customer name
- Customer position
- Company
- Profile image
- Rating
- Testimonial content
- Display order
- Status

---

# 37. Contact Information Management

The CMS should manage:

- Company name
- Company email
- Customer-service email
- Phone number
- Telegram
- WhatsApp
- Address
- Working hours
- Google Maps URL
- Facebook URL
- Instagram URL
- YouTube URL
- LinkedIn URL
- TikTok URL

---

# 38. Footer Management

The footer should support:

- Company logo
- Company description
- Contact information
- Useful links
- Customer-service links
- Social-media links
- Copyright text
- Payment-method logos
- Delivery-partner logos
- Newsletter form

---

# 39. Newsletter Subscriber Management

## Required Features

- Subscribe
- Unsubscribe
- View subscriber list
- Update subscriber status
- Search subscribers
- Export subscribers
- Track subscription date
- Prevent duplicate subscriptions

## Subscriber Fields

- Email
- Customer ID where available
- Subscription source
- Subscription date
- Status

---

# 40. Media Library

## Required Features

- Upload image
- Upload document
- Upload permitted video
- Search media
- Filter by file type
- Preview file
- Copy file URL
- Edit alternative text
- Rename file
- Delete file
- View file usage

## File Validation

- Allowed file types
- Maximum file size
- Secure file names
- Image compression
- Image resizing
- Duplicate-file handling

---

# 41. SEO Management

SEO fields should be available for:

- Products
- CMS pages
- Blog posts
- Homepage sections

## SEO Fields

- Meta title
- Meta description
- Meta keywords
- Canonical URL
- Open Graph title
- Open Graph description
- Open Graph image
- Robots index
- Robots follow

Also support:

- XML sitemap
- Robots.txt
- Friendly URLs
- Automatic slug creation
- Redirect management

---

# 42. Website Settings

## 42.1 General Settings

- Website name
- Website URL
- Website logo
- Admin logo
- Favicon
- Default language
- Default currency
- Time zone
- Date format
- Time format
- Number format

## 42.2 E-commerce Settings

- Default tax
- Product-review status
- Wishlist status
- Return period
- Cancellation period

## 42.3 Order Settings

- Order-number prefix
- Invoice-number prefix
- Automatic order confirmation
- Default order status
- Default payment status

## 42.4 Upload Settings

- Maximum product-image size
- Maximum document size
- Allowed image formats
- Image dimensions
- Image-compression quality

Shipping fees must be managed through the Shipping Method module.

---

# 43. Email Configuration and Templates

## 43.1 Email Configuration

- SMTP host
- SMTP port
- SMTP username
- SMTP password
- Encryption
- Sender name
- Sender email

## 43.2 Email Templates

- Customer registration
- Email verification
- Password reset
- Order confirmation
- Payment confirmation
- Order-status update
- Delivery confirmation
- Order cancellation
- Return approval
- Refund confirmation
- Contact-form response

## Email Template Fields

- Template name
- Subject
- Body
- Available variables
- Language
- Status

---

# 44. Activity Logs

Use:

```text
Package: Spatie Laravel Activity Log
```

Record:

- Administrator login
- Administrator logout
- Product created
- Product updated
- Product deleted
- Product availability changed
- Category updated
- Shipping method created
- Shipping method updated
- Shipping fee changed
- Order status changed
- Payment verified
- Refund processed
- Customer suspended
- CMS page published
- System setting changed

## Activity Log Fields

- Administrator
- Action
- Module
- Record ID
- Description
- Old values
- New values
- IP address
- User agent
- Date and time

## Activity Log Filters

- Search
- Administrator
- Module
- Action
- Date range
- Record details

---

# 45. AJAX DataTable Standards

Use:

```text
Package: Yajra Laravel DataTables
```

Apply server-side DataTables to:

- Administrators
- Roles
- Products
- Categories
- Brands
- Units
- Product attributes
- Customers
- Shipping methods
- Orders
- Payments
- Refunds
- Reviews
- CMS pages
- Banners
- Blogs
- FAQs
- Newsletter subscribers
- Activity logs

## Required Features

- Server-side pagination
- Search
- Sorting
- Advanced filters
- Date-range filter
- Status filter
- Responsive layout
- Loading state
- Empty state
- Permission-based actions
- Row selection
- Bulk actions
- Export
- Print
- AJAX refresh

---

# 46. Blade Template Structure

```text
resources/views/
├── admin/
│   ├── dashboard/
│   ├── users/
│   ├── roles/
│   ├── products/
│   ├── categories/
│   ├── brands/
│   ├── units/
│   ├── attributes/
│   ├── customers/
│   ├── shipping-methods/
│   ├── orders/
│   ├── payments/
│   ├── returns/
│   ├── promotions/
│   ├── reviews/
│   ├── cms/
│   ├── reports/
│   ├── settings/
│   └── activity-logs/
├── auth/
├── components/
├── layouts/
└── partials/
```

---

# 47. Reusable Blade Components

Create reusable components for:

- Text input
- Number input
- Password input
- Select input
- Multi-select
- Textarea
- Rich-text editor
- Checkbox
- Radio button
- Toggle switch
- File upload
- Image preview
- Validation error
- Status badge
- Action buttons
- Dashboard card
- Modal
- Confirmation dialog
- Breadcrumb
- Alert
- Empty state
- Filter panel
- Date-range picker

Example:

```blade
<x-admin.input
    name="name"
    label="Product Name"
    :value="old('name', $product->name ?? '')"
    required
/>
```

---

# 48. Admin Interface Requirements

The Bootstrap 5 Admin Dashboard should provide:

- Responsive desktop layout
- Responsive tablet layout
- Responsive mobile layout
- Collapsible sidebar
- Top navigation
- Breadcrumbs
- Clear page headings
- Consistent buttons
- Consistent forms
- Confirmation dialogs
- Loading indicators
- Success alerts
- Error alerts
- Empty states
- Form-validation feedback
- Tooltips
- Accessible labels
- Consistent spacing
- Consistent typography

---

# 49. RESTful API Architecture

## API Base

```text
/api/v1/
```

## Example Endpoints

```text
/api/v1/products
/api/v1/categories
/api/v1/brands
/api/v1/shipping-methods
/api/v1/cart
/api/v1/checkout
/api/v1/orders
/api/v1/payments
/api/v1/cms/pages
/api/v1/cms/banners
```

## Controller Location

```text
app/Http/Controllers/Api/V1/
```

## Resource Location

```text
app/Http/Resources/Api/V1/
```

## Request Location

```text
app/Http/Requests/Api/V1/
```

---

# 50. Product APIs

```text
GET /api/v1/products
GET /api/v1/products/{slug}
GET /api/v1/products/featured
GET /api/v1/products/new-arrivals
GET /api/v1/products/best-sellers
GET /api/v1/products/on-sale
GET /api/v1/products/{slug}/related
GET /api/v1/products/{slug}/reviews
```

## Product Filters

- Search
- Category
- Subcategory
- Brand
- Minimum price
- Maximum price
- Rating
- Color
- Size
- Product attribute
- Availability
- Discount
- Featured status

## Product Sorting

- Newest
- Oldest
- Price low to high
- Price high to low
- Most popular
- Best selling
- Highest rated

Availability values:

```text
in_stock
out_of_stock
```

---

# 51. Category and Brand APIs

## Category Endpoints

```text
GET /api/v1/categories
GET /api/v1/categories/tree
GET /api/v1/categories/{slug}
GET /api/v1/categories/{slug}/products
GET /api/v1/categories/{slug}/subcategories
```

## Brand Endpoints

```text
GET /api/v1/brands
GET /api/v1/brands/featured
GET /api/v1/brands/{slug}
GET /api/v1/brands/{slug}/products
```

---

# 52. Customer Authentication APIs

Use Laravel Sanctum.

```text
POST /api/v1/auth/register
POST /api/v1/auth/login
POST /api/v1/auth/logout
POST /api/v1/auth/forgot-password
POST /api/v1/auth/reset-password
POST /api/v1/auth/verify-email
POST /api/v1/auth/resend-verification
```

Protected routes:

```text
auth:sanctum
```

---

# 53. Customer Profile APIs

```text
GET    /api/v1/profile
PUT    /api/v1/profile
PUT    /api/v1/profile/password
POST   /api/v1/profile/image
DELETE /api/v1/profile
```

## Address Endpoints

```text
GET    /api/v1/addresses
POST   /api/v1/addresses
GET    /api/v1/addresses/{id}
PUT    /api/v1/addresses/{id}
DELETE /api/v1/addresses/{id}
PATCH  /api/v1/addresses/{id}/default
```

---

# 54. Shopping Cart APIs

```text
GET    /api/v1/cart
POST   /api/v1/cart/items
PUT    /api/v1/cart/items/{id}
DELETE /api/v1/cart/items/{id}
DELETE /api/v1/cart
GET    /api/v1/cart/summary
```

The API must validate:

- Product status
- Product availability
- Variant status
- Variant availability
- Current price
- Minimum quantity
- Maximum quantity

---

# 55. Shipping Method APIs

```text
GET /api/v1/shipping-methods
GET /api/v1/checkout/shipping-methods
```

Only active shipping methods should be returned.

Example response:

```json
{
    "success": true,
    "message": "Shipping methods retrieved successfully.",
    "data": [
        {
            "id": 1,
            "name": "Pick-up",
            "code": "pickup",
            "fixed_fee": 0
        },
        {
            "id": 2,
            "name": "Delivery",
            "code": "delivery",
            "fixed_fee": 2
        }
    ]
}
```

The backend must recalculate the selected fee during checkout.

---

# 56. Wishlist APIs

```text
GET    /api/v1/wishlist
POST   /api/v1/wishlist
DELETE /api/v1/wishlist/{productId}
POST   /api/v1/wishlist/{productId}/move-to-cart
```

---

# 57. Checkout APIs

```text
GET  /api/v1/checkout/summary
GET  /api/v1/checkout/shipping-methods
GET  /api/v1/checkout/payment-methods
POST /api/v1/checkout/validate
POST /api/v1/checkout/place-order
```

The checkout API must ensure:

- Products are active
- Products are in stock
- Prices are current
- Shipping method is active
- Fixed shipping fee comes from the database
- Order is created
- Order items are created
- Shipping snapshot is saved
- Payment transaction is created
- Cart is cleared only after success

---

# 58. Customer Order APIs

```text
GET  /api/v1/orders
GET  /api/v1/orders/{orderNumber}
POST /api/v1/orders/{orderNumber}/cancel
POST /api/v1/orders/{orderNumber}/return
GET  /api/v1/orders/{orderNumber}/tracking
GET  /api/v1/orders/{orderNumber}/invoice
POST /api/v1/orders/{orderNumber}/reorder
```

Customers must only access their own orders.

---

# 59. Payment APIs

```text
POST /api/v1/payments
GET  /api/v1/payments/{transactionNumber}
POST /api/v1/payments/{transactionNumber}/proof
POST /api/v1/payments/{transactionNumber}/retry
GET  /api/v1/payments/{transactionNumber}/status
POST /api/v1/payments/webhook/{gateway}
POST /api/v1/payments/callback/{gateway}
```

## Payment Security

- Validate gateway signatures
- Validate callbacks
- Validate webhook secrets
- Prevent duplicate transactions
- Use idempotency keys
- Log gateway requests
- Log gateway responses
- Never trust frontend payment amounts
- Match payment amounts with server-side order totals

---

# 60. Product Review APIs

```text
POST   /api/v1/products/{productId}/reviews
PUT    /api/v1/reviews/{id}
DELETE /api/v1/reviews/{id}
```

Validation:

- Customer must be authenticated
- Customer must have purchased the product
- Rating must be valid
- Review must belong to the customer
- Uploaded files must be validated

---

# 61. CMS APIs

## Settings

```text
GET /api/v1/cms/settings
```

## Homepage

```text
GET /api/v1/cms/homepage
GET /api/v1/cms/homepage/sections
```

## Pages

```text
GET /api/v1/cms/pages
GET /api/v1/cms/pages/{slug}
```

## Banners and Sliders

```text
GET /api/v1/cms/banners
GET /api/v1/cms/sliders
```

## Menus

```text
GET /api/v1/cms/menus/header
GET /api/v1/cms/menus/footer
GET /api/v1/cms/menus/mobile
```

## Blogs

```text
GET /api/v1/cms/blogs
GET /api/v1/cms/blogs/{slug}
GET /api/v1/cms/blog-categories
GET /api/v1/cms/blog-categories/{slug}/blogs
```

## FAQs

```text
GET /api/v1/cms/faqs
GET /api/v1/cms/faq-categories
```

## Testimonials

```text
GET /api/v1/cms/testimonials
```

## Contact

```text
GET  /api/v1/cms/contact-information
POST /api/v1/cms/contact
```

## Newsletter

```text
POST /api/v1/cms/newsletter/subscribe
POST /api/v1/cms/newsletter/unsubscribe
```

Only active and published CMS content should be returned.

---

# 62. API Response Format

## Successful Response

```json
{
    "success": true,
    "message": "Products retrieved successfully.",
    "data": [],
    "meta": {
        "current_page": 1,
        "per_page": 20,
        "total": 100,
        "last_page": 5
    }
}
```

## Created Response

```json
{
    "success": true,
    "message": "Order created successfully.",
    "data": {
        "order_number": "ORD-000001"
    }
}
```

## Validation Error

```json
{
    "success": false,
    "message": "Validation failed.",
    "errors": {
        "email": [
            "The email field is required."
        ]
    }
}
```

## Unauthorized Response

```json
{
    "success": false,
    "message": "Unauthenticated."
}
```

## Forbidden Response

```json
{
    "success": false,
    "message": "You do not have permission to perform this action."
}
```

## Not-Found Response

```json
{
    "success": false,
    "message": "Resource not found.",
    "data": null
}
```

---

# 63. API Technical Requirements

- RESTful endpoint naming
- API versioning
- Laravel API Resources
- Form Request validation
- Sanctum authentication
- Authorization policies
- Pagination
- Search
- Filtering
- Sorting
- Rate limiting
- Consistent JSON responses
- Standard HTTP status codes
- Exception handling
- CORS configuration
- API request logging
- API documentation
- Postman collection
- Payment idempotency
- Database transactions

---

# 64. Reporting Module

## 64.1 Sales Reports

- Daily sales
- Monthly sales
- Yearly sales
- Sales by product
- Sales by category
- Sales by brand
- Sales by customer
- Sales by location
- Sales by administrator
- Gross sales
- Net sales
- Product discount totals
- Tax totals
- Shipping-fee totals

## 64.2 Order Reports

- Orders by status
- Pending orders
- Completed orders
- Cancelled orders
- Refunded orders
- Orders by shipping method
- Average order value
- Order conversion rate

## 64.3 Payment Reports

- Successful payments
- Pending payments
- Failed payments
- Refunded payments
- Payments by method
- Payments by gateway
- Cash-on-delivery report
- ABA PayWay report
- Bakong report

## 64.4 Product Reports

- Best-selling products
- Slow-moving products
- In-stock products
- Out-of-stock products
- Most-viewed products
- Most-wishlisted products
- Product-profit report
- Product-return report

## 64.5 Customer Reports

- New customers
- Active customers
- Inactive customers
- Top customers
- Customer spending
- Customer order frequency
- Customer retention

## 64.6 Report Filters

- Date range
- Product
- Category
- Brand
- Customer
- Order status
- Payment status
- Payment method
- Shipping method
- Administrator

## 64.7 Export Options

- Excel
- CSV
- PDF
- Print

---

# 65. Database Requirements

## Main Tables

```text
users
roles
permissions
model_has_roles
model_has_permissions
role_has_permissions

customers
customer_addresses

categories
brands
units
attributes
attribute_values

products
product_categories
product_variants
product_variant_values
product_images

carts
cart_items

wishlists
wishlist_items

shipping_methods

orders
order_items
order_addresses
order_status_histories
order_notes

payments
payment_transactions
refunds

promotions

reviews
review_images

pages
homepage_sections
banners
sliders
menus
menu_items

blog_categories
blogs
blog_tags
blog_tag_relations

faq_categories
faqs
testimonials

contact_messages
newsletter_subscribers
media

settings
email_templates

activity_log
```

---

# 66. Important Database Fields

## Products Table

```text
id
name
slug
sku
barcode
category_id
brand_id
unit_id
cost_price
selling_price
sale_price
availability_status
status
featured_status
main_image
created_at
updated_at
deleted_at
```

Recommended availability:

```text
ENUM('in_stock', 'out_of_stock')
```

## Shipping Methods Table

```text
id
name
code
description
fixed_fee
status
display_order
created_at
updated_at
deleted_at
```

## Orders Table

Shipping-related fields:

```text
shipping_method_id
shipping_method_name
shipping_method_code
shipping_fee
```

---

# 67. Database Design Standards

- Use foreign-key constraints
- Add indexes to searchable columns
- Use unique indexes for SKU, slug and reference numbers
- Use soft deletes where restoration is required
- Use timestamps
- Use decimal columns for money
- Never use floating-point columns for money
- Save product snapshots in order items
- Save billing-address snapshots
- Save shipping-address snapshots
- Save shipping-method snapshots
- Use database transactions for checkout
- Use database transactions for payment operations

---

# 68. Laravel Backend Architecture

```text
app/
├── Enums/
├── Events/
├── Helpers/
├── Http/
│   ├── Controllers/
│   │   ├── Admin/
│   │   ├── Api/V1/
│   │   └── Auth/
│   ├── Middleware/
│   ├── Requests/
│   │   ├── Admin/
│   │   └── Api/V1/
│   └── Resources/
├── Jobs/
├── Listeners/
├── Mail/
├── Models/
├── Policies/
├── Services/
├── Support/
└── View/Components/
```

## Architecture Principles

- Keep controllers small
- Use Form Request classes
- Use service classes for business logic
- Use policies for authorization
- Use API Resources for JSON responses
- Use jobs for slow operations
- Use enums for statuses
- Use transactions for critical operations
- Avoid duplicated logic

---

# 69. Routing Structure

## Admin Routes

File:

```text
routes/admin.php
```

URL prefix:

```text
/admin
```

Route-name prefix:

```text
admin.
```

Middleware:

```text
auth
verified
permission middleware where required
```

## API Routes

File:

```text
routes/api.php
```

Prefix:

```text
/api/v1
```

Protected routes:

```text
auth:sanctum
```

---

# 70. Validation Requirements

Use Laravel Form Request classes for:

- Administrators
- Roles
- Products
- Categories
- Brands
- Units
- Attributes
- Customers
- Shipping methods
- Orders
- Payments
- Returns
- CMS forms
- API requests

Validation should cover:

- Required fields
- Data types
- Maximum lengths
- Unique values
- Foreign-key existence
- File types
- File sizes
- Image dimensions
- Price ranges
- Availability values
- Fixed shipping fees
- Date ranges
- Status values
- Permission rules

Validation messages must be clear and user-friendly.

---

# 71. Security Requirements

- CSRF protection
- XSS protection
- SQL-injection protection
- Password hashing
- Secure authentication
- Sanctum token authentication
- Role-based authorization
- Policies and Gates
- Login throttling
- API rate limiting
- Secure file uploads
- MIME-type validation
- File-size validation
- Safe file names
- HTTPS in production
- Secure cookies
- CORS configuration
- Payment-signature validation
- Webhook verification
- Sensitive-data encryption
- Activity logs
- Database backups
- Environment-variable protection

---

# 72. Performance Requirements

- Use eager loading
- Prevent N+1 queries
- Add database indexes
- Use server-side DataTables
- Use pagination
- Cache CMS data
- Cache website settings
- Cache categories
- Cache menus
- Queue emails
- Queue large imports
- Queue large exports
- Resize and compress images
- Use WebP where possible
- Minify assets
- Enable Laravel production optimization
- Support Redis later where necessary
- Support CDN integration later where necessary

---

# 73. Queue Requirements

Queue the following:

- Email sending
- Product import
- Large report export
- Image processing
- Newsletter email campaigns
- Payment follow-up tasks

Production must run a queue worker.

---

# 74. Scheduler Requirements

Laravel Scheduler may handle:

- Expiring promotions
- Activating scheduled banners
- Deactivating expired banners
- Publishing scheduled blogs
- Daily sales summaries
- Database-cleanup tasks
- Temporary-file cleanup

Production must configure the Laravel scheduler cron job.

---

# 75. Logging and Error Handling

The system must provide:

- Application logs
- API error logs
- Payment logs
- Webhook logs
- Queue-failure logs
- Import-error logs
- Administrator activity logs

Production errors should:

- Show a friendly message
- Hide sensitive technical details
- Record detailed information
- Include a traceable reference where useful

---

# 76. Testing Requirements

## Unit Tests

- Product-price calculation
- Product-discount calculation
- Tax calculation
- Fixed shipping-fee calculation
- Order-total calculation
- Payment-amount validation

## Feature Tests

- Administrator login
- Permission enforcement
- Product creation
- Product update
- Product-availability update
- Shipping-method CRUD
- Shipping-fee update
- Customer registration
- Shopping cart
- Checkout
- Order creation
- Payment verification
- Refund processing
- CMS publication

## API Tests

- Product endpoints
- Category endpoints
- Brand endpoints
- Customer authentication
- Protected routes
- Cart endpoints
- Shipping-method endpoints
- Checkout endpoint
- Order endpoints
- Payment endpoints
- CMS endpoints
- Validation errors
- Authorization
- Rate limiting

## Security Tests

- Unauthorized access
- Forbidden actions
- File-upload validation
- SQL-injection attempts
- XSS input
- CSRF validation
- Duplicate-payment prevention
- Shipping-fee manipulation attempts

---

# 77. Development Phases

## Phase 1: Existing Project Audit

- Back up the existing project
- Review Laravel version
- Review PHP version
- Review MySQL database
- Review Blade templates
- Review controllers
- Review models
- Review routes
- Review authentication
- Identify reusable modules
- Identify deprecated code
- Identify modules to replace
- Prepare migration strategy

## Phase 2: Laravel 12 Foundation

- Install or upgrade Laravel 12
- Configure PHP 8.2+
- Configure MySQL
- Configure environment variables
- Configure application timezone
- Configure email
- Configure storage
- Configure logging
- Configure queues
- Configure scheduler


## Phase 3: Admin Dashboard UI

- Create Bootstrap 5 layout
- Create top navigation
- Create sidebar
- Create footer
- Create breadcrumbs
- Create reusable Blade components
- Create form styles
- Create DataTable styles
- Create modal components
- Create alert components
- Make the interface responsive

## Phase 4: Authentication and Permissions

- Administrator login
- Forgot password
- Reset password
- Administrator management
- Role management
- Permission management
- Route protection
- Policy implementation
- Activity logging

## Phase 5: Product Master Data

- Categories
- Subcategories
- Brands
- Units
- Product statuses

## Phase 6: Product Management

- Product CRUD
- Product variants
- Product images
- Product gallery
- Product prices
- In-stock and out-of-stock status
- SEO fields
- Import
- Export
- Product DataTable

## Phase 7: Customer Management

- Customer accounts
- Customer addresses
- Customer statuses
- Customer history
- Customer DataTable
- Customer reports

## Phase 8: Shipping Method Management

- Shipping-method migration
- Shipping-method model
- Shipping-method CRUD
- Fixed-fee validation
- Pick-up seeder
- Delivery seeder
- Shipping permissions
- Shipping DataTable
- Shipping API
- Checkout integration

## Phase 9: Shopping Cart and Checkout

- Shopping cart
- Product validation
- Availability validation
- Product-discount calculation
- Tax calculation
- Fixed shipping-fee calculation
- Checkout validation
- Order creation
- Shipping-method snapshot
- Payment transaction
- Cart clearing

## Phase 10: Order Management

- Order DataTable
- Order details
- Order statuses
- Delivery statuses
- Status history
- Manual orders
- Invoices
- Packing slips
- Cancellation
- Return requests

## Phase 11: Payment Management

- Payment methods
- Payment proofs
- ABA PayWay integration
- Bakong integration
- Payment verification
- Webhook processing
- Refunds
- Payment reports

## Phase 12: CMS Development

- Pages
- Homepage sections
- Banners
- Sliders
- Menus
- Blogs
- FAQs
- Testimonials
- Footer
- Contact information
- Newsletter subscribers
- Media library
- SEO management

## Phase 13: RESTful API

- API response structure
- Product APIs
- Category APIs
- Brand APIs
- Customer authentication
- Customer profile
- Shopping-cart APIs
- Shipping-method APIs
- Checkout API
- Order APIs
- Payment APIs
- CMS APIs
- API documentation

## Phase 14: Dashboard and Reports

- Summary cards
- Chart.js charts
- Sales reports
- Order reports
- Payment reports
- Product reports
- Customer reports
- Shipping-method reports
- Excel export
- CSV export
- PDF export

## Phase 15: Testing

- Unit testing
- Feature testing
- API testing
- Permission testing
- Security testing
- Performance testing
- User-acceptance testing

---

# 78. Minimum Viable Product

The first production version should include:

- Administrator authentication
- Roles and permissions
- Activity logs
- Dashboard
- Categories
- Subcategories
- Brands
- Units
- Product management
- Product images
- In-stock and out-of-stock availability
- Customer management
- Customer addresses
- Shopping cart
- Shipping-method CRUD
- Pick-up fee of $0
- Delivery fee of $2
- Checkout
- Order management
- Payment management
- Returns and refunds
- CMS pages
- Banners
- Sliders
- FAQs
- Website settings
- Product APIs
- Category APIs
- Brand APIs
- Customer-authentication APIs
- Cart APIs
- Shipping-method APIs
- Checkout API
- Order APIs
- Payment APIs
- CMS APIs
- Basic reports
- API documentation

---

# 80. Final Technical Specification

```text
Backend Framework: Laravel 12
Backend Language: PHP 8.2+
Admin Interface: Laravel Blade Templates
Admin Styling: Bootstrap 5
Admin Interactivity: JavaScript, AJAX and jQuery where required
Data Tables: Yajra Laravel DataTables
Charts: Chart.js
API Authentication: Laravel Sanctum
Database: MySQL
Permissions: Spatie Laravel Permission
Activity Logs: Spatie Laravel Activity Log
API Format: RESTful JSON API
```

The Admin Dashboard, CMS, reports, product management, customer management, shipping-method management, order management, payment management and system settings will be developed using Laravel Blade Templates and Bootstrap 5.

The customer-facing E-commerce website will consume the Laravel RESTful JSON API. Protected customer endpoints will use Laravel Sanctum authentication.
