aboutsummaryrefslogtreecommitdiffstats
path: root/docs/implementation.md
blob: 03d8c430cd9e176f4464607527c067787f628593 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
# Implementation Guide

This guide provides practical steps to implement the e-commerce platform based on the project plan.

## Getting Started

### 1. Development Environment Setup

```bash
# Create project directory structure
mkdir -p ecom/{frontend,backend,admin,shared}

# Initialize frontend (Next.js)
cd ecom/frontend
npx create-next-app . --typescript --tailwind --eslint

# Initialize backend (Express.js + MongoDB)
cd ../backend
npm init -y
npm install express mongoose dotenv cors helmet jsonwebtoken bcrypt stripe

# Create basic directory structure for backend
mkdir -p config controllers middleware models routes services utils
touch server.js .env .env.example .gitignore README.md
```

### 2. Frontend Implementation Steps

#### Step 1: Set up basic components
- Create layout components (header, footer, navigation)
- Set up routing structure
- Implement basic styling with Tailwind CSS

#### Step 2: Key pages implementation
- Homepage with featured products and promotions
- Product listing page with filtering
- Product detail page
- Cart page
- Checkout flow
- User account pages

```jsx
// Example: Product Card Component (frontend/src/components/ProductCard.jsx)
import Image from 'next/image';
import Link from 'next/link';

const ProductCard = ({ product }) => {
  return (
    <div className="group relative">
      <div className="aspect-h-1 aspect-w-1 w-full overflow-hidden rounded-md bg-gray-200 lg:aspect-none group-hover:opacity-75 lg:h-80">
        <Image
          src={product.imageSrc}
          alt={product.imageAlt}
          className="h-full w-full object-cover object-center lg:h-full lg:w-full"
          width={500}
          height={500}
        />
      </div>
      <div className="mt-4 flex justify-between">
        <div>
          <h3 className="text-sm text-gray-700">
            <Link href={`/products/${product.id}`}>
              <span aria-hidden="true" className="absolute inset-0" />
              {product.name}
            </Link>
          </h3>
          <p className="mt-1 text-sm text-gray-500">{product.color}</p>
        </div>
        <p className="text-sm font-medium text-gray-900">{product.price}</p>
      </div>
    </div>
  );
};

export default ProductCard;
```

#### Step 3: State management
- Implement context providers for:
  - Shopping cart
  - User authentication
  - Product filtering

```jsx
// Example: CartContext (frontend/src/contexts/CartContext.jsx)
import { createContext, useContext, useReducer, useEffect } from 'react';

const CartContext = createContext();

const cartReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_ITEM':
      // Check if item exists
      const existingItemIndex = state.items.findIndex(
        (item) => item.id === action.payload.id && 
                  item.selectedSize === action.payload.selectedSize
      );
      
      if (existingItemIndex >= 0) {
        // Item exists, update quantity
        const updatedItems = [...state.items];
        updatedItems[existingItemIndex].quantity += action.payload.quantity;
        
        return {
          ...state,
          items: updatedItems,
        };
      }
      
      // Item doesn't exist, add new
      return {
        ...state,
        items: [...state.items, action.payload],
      };
      
    case 'REMOVE_ITEM':
      return {
        ...state,
        items: state.items.filter(
          (item) => !(item.id === action.payload.id && 
                     item.selectedSize === action.payload.selectedSize)
        ),
      };
      
    case 'UPDATE_QUANTITY':
      return {
        ...state,
        items: state.items.map((item) => {
          if (item.id === action.payload.id && 
              item.selectedSize === action.payload.selectedSize) {
            return {
              ...item,
              quantity: action.payload.quantity,
            };
          }
          return item;
        }),
      };
      
    case 'CLEAR_CART':
      return {
        ...state,
        items: [],
      };
      
    default:
      return state;
  }
};

export const CartProvider = ({ children }) => {
  const [state, dispatch] = useReducer(cartReducer, {
    items: [],
  });
  
  // Load cart from localStorage on mount
  useEffect(() => {
    try {
      const savedCart = localStorage.getItem('cart');
      if (savedCart) {
        const parsedCart = JSON.parse(savedCart);
        dispatch({ type: 'REPLACE_CART', payload: parsedCart });
      }
    } catch (error) {
      console.error('Error loading cart from localStorage:', error);
    }
  }, []);
  
  // Save cart to localStorage on update
  useEffect(() => {
    try {
      localStorage.setItem('cart', JSON.stringify(state.items));
    } catch (error) {
      console.error('Error saving cart to localStorage:', error);
    }
  }, [state.items]);
  
  const addItem = (product, quantity = 1, selectedSize) => {
    dispatch({
      type: 'ADD_ITEM',
      payload: { ...product, quantity, selectedSize },
    });
  };
  
  const removeItem = (productId, selectedSize) => {
    dispatch({
      type: 'REMOVE_ITEM',
      payload: { id: productId, selectedSize },
    });
  };
  
  const updateQuantity = (productId, selectedSize, quantity) => {
    dispatch({
      type: 'UPDATE_QUANTITY',
      payload: { id: productId, selectedSize, quantity },
    });
  };
  
  const clearCart = () => {
    dispatch({ type: 'CLEAR_CART' });
  };
  
  const cartTotal = state.items.reduce(
    (total, item) => total + item.price * item.quantity,
    0
  );
  
  const itemCount = state.items.reduce(
    (count, item) => count + item.quantity,
    0
  );
  
  return (
    <CartContext.Provider
      value={{
        items: state.items,
        addItem,
        removeItem,
        updateQuantity,
        clearCart,
        cartTotal,
        itemCount,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

export const useCart = () => useContext(CartContext);
```

### 3. Backend Implementation Steps

#### Step 1: Database models
- Create schemas for products, users, orders
- Set up database connection

```javascript
// Example: Product Model (backend/models/Product.js)
const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  slug: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  description: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  compareAtPrice: {
    type: Number,
    min: 0
  },
  images: [{
    url: String,
    alt: String
  }],
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category',
    required: true
  },
  variants: [{
    color: String,
    size: String,
    inventory: Number
  }],
  tags: [String],
  featured: {
    type: Boolean,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
}, { timestamps: true });

// Add index for search
productSchema.index({ 
  name: 'text', 
  description: 'text',
  tags: 'text'
});

module.exports = mongoose.model('Product', productSchema);
```

#### Step 2: API endpoints
- Create RESTful routes for products, users, orders
- Implement authentication middleware

```javascript
// Example: Product Routes (backend/routes/products.js)
const express = require('express');
const router = express.Router();
const productController = require('../controllers/productController');
const { authenticate, isAdmin } = require('../middleware/authMiddleware');

// Public routes
router.get('/', productController.getAllProducts);
router.get('/featured', productController.getFeaturedProducts);
router.get('/category/:categoryId', productController.getProductsByCategory);
router.get('/search', productController.searchProducts);
router.get('/:id', productController.getProductById);
router.get('/slug/:slug', productController.getProductBySlug);

// Protected routes (admin only)
router.post('/', authenticate, isAdmin, productController.createProduct);
router.put('/:id', authenticate, isAdmin, productController.updateProduct);
router.delete('/:id', authenticate, isAdmin, productController.deleteProduct);
router.post('/bulk', authenticate, isAdmin, productController.bulkImportProducts);

module.exports = router;
```

#### Step 3: Payment integration
- Set up Stripe API for payment processing
- Implement checkout logic

```javascript
// Example: Payment Controller (backend/controllers/paymentController.js)
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const Order = require('../models/Order');
const Product = require('../models/Product');

exports.createCheckoutSession = async (req, res) => {
  try {
    const { items, shippingAddress } = req.body;
    
    // Validate cart items and get from database to ensure price integrity
    const productIds = items.map(item => item.id);
    const products = await Product.find({ _id: { $in: productIds } });
    
    // Map products to line items for Stripe
    const lineItems = items.map(item => {
      const product = products.find(p => p._id.toString() === item.id);
      
      if (!product) {
        throw new Error(`Product not found: ${item.id}`);
      }
      
      return {
        price_data: {
          currency: 'inr',
          product_data: {
            name: product.name,
            images: product.images.map(img => img.url),
          },
          unit_amount: Math.round(product.price * 100), // Stripe requires amount in cents
        },
        quantity: item.quantity,
      };
    });
    
    // Create a new order in pending state
    const order = new Order({
      user: req.user ? req.user._id : null,
      items: items.map(item => ({
        product: item.id,
        quantity: item.quantity,
        price: products.find(p => p._id.toString() === item.id).price,
        selectedVariant: {
          size: item.selectedSize,
          color: item.selectedColor
        }
      })),
      shippingAddress,
      total: items.reduce((sum, item) => {
        const product = products.find(p => p._id.toString() === item.id);
        return sum + (product.price * item.quantity);
      }, 0),
      status: 'pending'
    });
    
    await order.save();
    
    // Create Stripe checkout session
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: lineItems,
      mode: 'payment',
      success_url: `${process.env.FRONTEND_URL}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${process.env.FRONTEND_URL}/cart`,
      metadata: {
        orderId: order._id.toString()
      }
    });
    
    res.json({ id: session.id, url: session.url });
  } catch (error) {
    console.error('Payment session error:', error);
    res.status(500).json({ error: error.message });
  }
};

exports.handleWebhook = async (req, res) => {
  const signature = req.headers['stripe-signature'];
  
  try {
    const event = stripe.webhooks.constructEvent(
      req.body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET
    );
    
    if (event.type === 'checkout.session.completed') {
      const session = event.data.object;
      const orderId = session.metadata.orderId;
      
      // Update order status to paid
      await Order.findByIdAndUpdate(orderId, {
        status: 'paid',
        paymentId: session.payment_intent
      });
      
      // Here you would also update inventory, send confirmation emails, etc.
    }
    
    res.json({ received: true });
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(400).send(`Webhook Error: ${error.message}`);
  }
};
```

### 4. Admin Dashboard Implementation

- Implement pages for product, order, and user management
- Create forms for product creation and editing
- Develop dashboard for sales analytics

### 5. Deployment Strategy

#### Development Environment
- Local development with Docker

#### Staging Environment
- AWS/Vercel deployment
- Continuous integration with GitHub Actions

#### Production Environment
- Load-balanced setup
- Database backups
- CDN for static assets

## Key Features Implementation Details

### 1. Country/Currency Selector

```jsx
// Example component
import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';

const countryCurrencyMap = {
  US: { currency: 'USD', symbol: '$' },
  IN: { currency: 'INR', symbol: '₹' },
  GB: { currency: 'GBP', symbol: '£' },
  // Add more countries as needed
};

export default function CurrencySelector() {
  const [selectedCountry, setSelectedCountry] = useState('IN');
  const router = useRouter();
  
  // Effect to set country based on user's location or saved preference
  useEffect(() => {
    const savedCountry = localStorage.getItem('selectedCountry');
    if (savedCountry) {
      setSelectedCountry(savedCountry);
    } else {
      // Could add geolocation API to auto-detect
    }
  }, []);
  
  // Update when user changes selection
  const handleCountryChange = (e) => {
    const country = e.target.value;
    setSelectedCountry(country);
    localStorage.setItem('selectedCountry', country);
    
    // Force refresh to update prices
    router.reload();
  };
  
  return (
    <div className="relative">
      <select
        value={selectedCountry}
        onChange={handleCountryChange}
        className="block appearance-none bg-white border border-gray-300 px-4 py-2 pr-8 rounded shadow leading-tight focus:outline-none focus:shadow-outline"
      >
        <option value="IN">India ()</option>
        <option value="US">United States ($)</option>
        <option value="GB">United Kingdom (£)</option>
        {/* Add more countries */}
      </select>
      <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
        <svg className="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
          <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
        </svg>
      </div>
    </div>
  );
}
```

### 2. Responsive Product Gallery

```jsx
// Example implementation
import { useState } from 'react';
import Image from 'next/image';

export default function ProductGallery({ images }) {
  const [mainImage, setMainImage] = useState(images[0]);
  
  return (
    <div className="grid gap-4">
      <div className="relative h-96 overflow-hidden rounded-lg">
        <Image
          src={mainImage.url}
          alt={mainImage.alt}
          layout="fill"
          objectFit="cover"
          className="w-full h-full object-center object-cover"
        />
      </div>
      <div className="grid grid-cols-5 gap-2">
        {images.map((image, i) => (
          <button
            key={i}
            onClick={() => setMainImage(image)}
            className={`relative h-20 overflow-hidden rounded-md ${
              mainImage.url === image.url ? 'ring-2 ring-indigo-500' : ''
            }`}
          >
            <Image
              src={image.url}
              alt={image.alt}
              layout="fill"
              objectFit="cover"
              className="w-full h-full object-center object-cover"
            />
          </button>
        ))}
      </div>
    </div>
  );
}
```

### 3. Promotional Banner Component

```jsx
// Example implementation
import { useState, useEffect } from 'react';

export default function PromoBanner({ code, message, expiry }) {
  const [isVisible, setIsVisible] = useState(true);
  
  // Check if banner should be shown (e.g., not dismissed recently)
  useEffect(() => {
    const bannerDismissed = localStorage.getItem('promoBannerDismissed');
    if (bannerDismissed) {
      const dismissTime = parseInt(bannerDismissed);
      // Show again after 1 day
      if (Date.now() - dismissTime < 24 * 60 * 60 * 1000) {
        setIsVisible(false);
      }
    }
  }, []);
  
  const handleDismiss = () => {
    setIsVisible(false);
    localStorage.setItem('promoBannerDismissed', Date.now().toString());
  };
  
  if (!isVisible) return null;
  
  return (
    <div className="bg-indigo-600 py-3">
      <div className="mx-auto max-w-7xl px-3 sm:px-6 lg:px-8">
        <div className="flex flex-wrap items-center justify-between">
          <div className="flex w-0 flex-1 items-center">
            <span className="flex rounded-lg bg-indigo-800 p-2">
              <svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" />
              </svg>
            </span>
            <p className="ml-3 font-medium text-white">
              <span className="md:hidden">{message}</span>
              <span className="hidden md:inline">
                {message} Use code <span className="font-bold">{code}</span> at checkout
              </span>
            </p>
          </div>
          <div className="order-3 mt-2 w-full flex-shrink-0 sm:order-2 sm:mt-0 sm:w-auto">
            <a
              href="#"
              className="flex items-center justify-center rounded-md border border-transparent bg-white px-4 py-2 text-sm font-medium text-indigo-600 shadow-sm hover:bg-indigo-50"
            >
              Shop Now
            </a>
          </div>
          <div className="order-2 flex-shrink-0 sm:order-3 sm:ml-3">
            <button
              type="button"
              onClick={handleDismiss}
              className="-mr-1 flex rounded-md p-2 hover:bg-indigo-500 focus:outline-none focus:ring-2 focus:ring-white sm:-mr-2"
            >
              <span className="sr-only">Dismiss</span>
              <svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
```

## Testing and Quality Assurance

### Unit Testing
```bash
# Frontend testing
cd frontend
npm test

# Backend testing
cd ../backend
npm test
```

### End-to-End Testing
```bash
# Install Cypress
cd frontend
npm install cypress --save-dev

# Run E2E tests
npx cypress open
```

## Performance Optimization Strategies

1. **Image Optimization**
   - Use Next.js Image component
   - Implement lazy loading
   - Serve responsive images

2. **Code Splitting**
   - Leverage Next.js automatic code splitting
   - Use dynamic imports for large components

3. **Server-Side Rendering**
   - Use SSR for product listings and detail pages
   - Implement Incremental Static Regeneration for frequently updated pages

4. **API Response Caching**
   - Implement Redis for caching
   - Add HTTP cache headers

## Security Best Practices

1. **Authentication**
   - Implement JWT with refresh tokens
   - Store tokens securely in HTTP-only cookies

2. **API Security**
   - Implement rate limiting
   - Use CORS protection
   - Validate all inputs

3. **Payment Data**
   - Use Stripe Elements for secure payment form
   - Never store sensitive payment information

## Ongoing Maintenance Plan

1. Regular dependency updates
2. Security patches
3. Performance monitoring
4. Backup strategy
5. Scaling plan as traffic increases