npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

saksh-cart

v1.0.8

Published

A comprehensive e-commerce package with shopping cart, order management, checkout, coupon management, reporting, refund management, IPN handling, and wishlist features.

Downloads

9

Readme

SakshCart

SakshCart is a Node.js package that provides a comprehensive shopping cart service with various functionalities such as adding items to the cart, viewing the cart, removing items, clearing the cart, checking out, validating coupons, and generating various reports. It also includes wishlist functionality.

Features

  • Add items to the cart
  • View cart items
  • Remove items from the cart
  • Clear the cart
  • Checkout with check payment
  • Validate coupons
  • Generate sales reports
  • Generate user reports
  • Generate monthly sales reports
  • Generate top-selling products reports
  • Generate user order count reports
  • Add items to the wishlist
  • View wishlist items
  • Remove items from the wishlist

Installation

Install the package via npm:

npm install saksh-cart

Usage

Setting Up

Import the package:


const express = require('express');
const mongoose = require('mongoose');

// Import services from the local index file
const { SakshCartService, SakshCheckoutService, SakshCouponService, SakshOrderService, SakshWishlistService, SakshReportingService } = require('saksh-cart');

const app = express();
const PORT = process.env.PORT || 5000;

// Middleware
app.use(express.json());

// Simulate logged-in user
const loggedInUserId = 'user123';

// Connect to the database
mongoose.connect('mongodb://localhost:27017/sakshCart', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => {
    console.log('Database connected');
}).catch(err => {
    console.error('Database connection error', err);
});

// Initialize services
const cartService = new SakshCartService();
const checkoutService = new SakshCheckoutService();
const couponService = new SakshCouponService();
const orderService = new SakshOrderService();
const reportingService = new SakshReportingService();
const wishlistService = new SakshWishlistService();
// Routes

// Add item to cart
app.post('/api/cart/add', async (req, res) => {
    try {
        const { cartData } = req.body;
        const items = await cartService.addToCart(loggedInUserId, cartData);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// View cart
app.get('/api/cart', async (req, res) => {
    try {
        const items = await cartService.viewCart(loggedInUserId);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Remove item from cart
app.delete('/api/cart/remove', async (req, res) => {
    try {
        const { itemId } = req.body;
        const items = await cartService.removeFromCart(loggedInUserId, itemId);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Clear cart
app.delete('/api/cart/clear', async (req, res) => {
    try {
        const items = await cartService.clearCart(loggedInUserId);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Checkout with check payment
app.post('/api/checkout', async (req, res) => {
    try {
        const { couponCode } = req.body;
        const result = await checkoutService.sakshProcessCheckoutWithCheck(loggedInUserId, couponCode);
        res.status(200).json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Validate coupon
app.post('/api/coupon/validate', async (req, res) => {
    try {
        const { couponCode } = req.body;
        const coupon = await couponService.sakshValidateCoupon(couponCode);
        res.status(200).json(coupon);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Generate user report
app.get('/api/reporting/user', async (req, res) => {
    try {
        const report = await reportingService.sakshGenerateUserReport(loggedInUserId);
        res.status(200).json(report);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Generate monthly sales report
app.get('/api/reporting/monthly-sales', async (req, res) => {
    try {
        const report = await reportingService.sakshGenerateMonthlySalesReport();
        res.status(200).json(report);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Generate top selling products report
app.get('/api/reporting/top-selling-products', async (req, res) => {
    try {
        const report = await reportingService.sakshGenerateTopSellingProductsReport();
        res.status(200).json(report);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Generate user order count report
app.get('/api/reporting/user-order-count', async (req, res) => {
    try {
        const report = await reportingService.sakshGenerateUserOrderCountReport();
        res.status(200).json(report);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Wishlist routes

// Add item to wishlist
app.post('/api/wishlist/add', async (req, res) => {
    try {
        const { itemId } = req.body;
        const items = await wishlistService.addToWishlist(loggedInUserId, itemId);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// View wishlist
app.get('/api/wishlist', async (req, res) => {
    try {
        const items = await wishlistService.viewWishlist(loggedInUserId);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Remove item from wishlist
app.delete('/api/wishlist/remove', async (req, res) => {
    try {
        const { itemId } = req.body;
        const items = await wishlistService.removeFromWishlist(loggedInUserId, itemId);
        res.status(200).json(items);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});


// Error handling middleware
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

API Endpoints

Add Item to Cart

curl -X POST http://localhost:5000/api/cart/add \
-H "Content-Type: application/json" \
-d '{
    "cartData": {
        "itemId": "item456",
        "quantity": 2,
        "price": 100,
        "sellerId": "seller789",
        "shippingPrice": 10
    }
}'

View Cart

curl -X GET http://localhost:5000/api/cart

Remove Item from Cart

curl -X DELETE http://localhost:5000/api/cart/remove \
-H "Content-Type: application/json" \
-d '{
    "itemId": "item456"
}'

Clear Cart

curl -X DELETE http://localhost:5000/api/cart/clear

Checkout with Check Payment

curl -X POST http://localhost:5000/api/checkout \
-H "Content-Type: application/json" \
-d '{
    "couponCode": "DISCOUNT10"
}'

Validate Coupon

curl -X POST http://localhost:5000/api/coupon/validate \
-H "Content-Type: application/json" \
-d '{
    "couponCode": "DISCOUNT10"
}'

Generate User Report

curl -X GET http://localhost:5000/api/reporting/user

Generate Monthly Sales Report

curl -X GET http://localhost:5000/api/reporting/monthly-sales

Generate Top Selling Products Report

curl -X GET http://localhost:5000/api/reporting/top-selling-products

Generate User Order Count Report

curl -X GET http://localhost:5000/api/reporting/user-order-count

Wishlist Endpoints

Add Item to Wishlist

curl -X POST http://localhost:5000/api/wishlist/add \
-H "Content-Type: application/json" \
-d '{
    "itemId": "item456"
}'

View Wishlist

curl -X GET http://localhost:5000/api/wishlist

Remove Item from Wishlist

curl -X DELETE http://localhost:5000/api/wishlist/remove \
-H "Content-Type: application/json" \
-d '{
    "itemId": "item456"
}'

Events

You can handle these events in your application like this:

const SakshCartService = require('./path/to/SakshCartService');
const cartService = new SakshCartService();

cartService.on('itemAdded', ({ userId, cartItem }) => {
console.log(`Item added to cart for user ${userId}:`, cartItem);
});

cartService.on('cartViewed', ({ userId, items }) => {
console.log(`Cart viewed for user ${userId}:`, items);
});

cartService.on('itemRemoved', ({ userId, itemId }) => {
console.log(`Item removed from cart for user ${userId}:`, itemId);
});

cartService.on('cartCleared', (userId) => {
console.log(`Cart cleared for user ${userId}`);
});





 
const checkoutService = new sakshCheckoutService();

checkoutService.on('couponApplied', ({ userId, couponCode, discount }) => {
console.log(`Coupon applied for user ${userId}: ${couponCode} with ${discount}% discount`);
});

checkoutService.on('orderCreated', ({ userId, order }) => {
console.log(`Order created for user ${userId}:`, order);
});

checkoutService.on('cartCleared', (userId) => {
console.log(`Cart cleared for user ${userId}`);
});




const couponService = new sakshCouponService();

couponService.on('couponValid', ({ couponCode, discount }) => {
console.log(`Coupon validated: ${couponCode} with ${discount}% discount`);
});

couponService.on('couponInvalid', ({ couponCode }) => {
console.log(`Invalid coupon code: ${couponCode}`);
});


const orderService = new sakshOrderService();

orderService.on('orderCreated', ({ orderId, status, sellerIds }) => {
console.log(`Order created for user ${userId}:`, order);
});


orderService.on('orderCreationFailed', ({ userId, error }) => {
console.error(`Order creation failed for user ${userId}:`, error);
});

orderService.on('orderViewed', ({ orderId, order }) => {
console.log(`Order viewed: ${orderId}`, order);
});

orderService.on('orderViewFailed', ({ orderId, error }) => {
console.error(`Order view failed for order ${orderId}:`, error);
});

orderService.on('ordersViewedByUser', ({ userId, orders }) => {
console.log(`Orders viewed for user ${userId}:`, orders);
});

orderService.on('ordersViewByUserFailed', ({ userId, error }) => {
console.error(`Orders view failed for user ${userId}:`, error);
});

//  this.emit('orderStatusUpdated', { orderId, status, sellerIds });
orderService.on('orderStatusUpdated', ({ orderId, status, sellerIds }) => {
console.log(`Order status updated for order ${orderId}: ${status}`);
});

orderService.on('orderStatusUpdateFailed', ({ orderId, error }) => {
console.error(`Order status update failed for order ${orderId}:`, error);
});



 
const wishlistService = new SakshWishlistService();

wishlistService.on('itemAddedToWishlist', ({ userId, wishlistItem }) => {
console.log(`Item added to wishlist for user ${userId}:`, wishlistItem);
});

wishlistService.on('wishlistViewed', ({ userId, items }) => {
console.log(`Wishlist viewed for user ${userId}:`, items);
});

wishlistService.on('itemRemovedFromWishlist', ({ userId, itemId }) => {
console.log(`Item removed from wishlist for user ${userId}:`, itemId);
});


how to send email notification when order received

// Dummy function to get user email by user ID
function getUserEmail(userId) {
    // Dummy data for demonstration purposes
    const userDatabase = {
        'user1': '[email protected]',
        'user2': '[email protected]',
        'admin': '[email protected]',
    };

    return userDatabase[userId] || '[email protected]';
}

const cartService = new SakshCartService();
const orderService = new SakshOrderService();
const couponService = new SakshCouponService();
const wishlistService = new SakshWishlistService();

// SakshCartService Events
cartService.on('itemAdded', async ({ userId, cartItem, sellerId }) => {
    const subject = 'Item Added to Cart';
    const text = `User ${userId} added item ${cartItem.itemId} to their cart.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
    await sendEmail(getUserEmail(userId), subject, text); // Notify buyer
    await sendEmail(getUserEmail(sellerId), subject, `Seller ${sellerId}, ${text}`); // Notify seller
});

cartService.on('cartViewed', async ({ userId, items }) => {
    const subject = 'Cart Viewed';
    const text = `User ${userId} viewed their cart. Items: ${JSON.stringify(items)}`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
});

cartService.on('itemRemoved', async ({ userId, itemId }) => {
    const subject = 'Item Removed from Cart';
    const text = `User ${userId} removed item ${itemId} from their cart.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
    await sendEmail(getUserEmail(userId), subject, text); // Notify buyer
});

cartService.on('cartCleared', async (userId) => {
    const subject = 'Cart Cleared';
    const text = `User ${userId} cleared their cart.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
    await sendEmail(getUserEmail(userId), subject, text); // Notify buyer
});

// SakshOrderService Events
orderService.on('orderCreated', async ({ userId, order, sellerIds }) => {
    const subject = 'Order Created';
    const text = `User ${userId} created an order with ID ${order._id}. Total: ${order.total}`;
    
    // Notify admin
    await sendEmail(getUserEmail('admin'), subject, text);
    // Notify buyer
    await sendEmail(getUserEmail(userId), subject, text);
    
    // Notify each seller
    for (const sellerId of sellerIds) {
        await sendEmail(getUserEmail(sellerId), subject, `Seller ${sellerId}, ${text}`);
    }
});

orderService.on('orderStatusUpdated', async ({ orderId, status, sellerIds }) => {
    const subject = 'Order Status Updated';
    const text = `Order ${orderId} status has been updated to ${status}.`;
    
    // Notify admin
    await sendEmail(getUserEmail('admin'), subject, text);
    // Notify buyer
    await sendEmail(getUserEmail('user1'), subject, text); // Assuming 'user1' is the buyer for demo purposes
    
    // Notify each seller
    for (const sellerId of sellerIds) {
        await sendEmail(getUserEmail(sellerId), subject, `Seller ${sellerId}, ${text}`);
    }
});

// SakshCouponService Events
couponService.on('couponValid', async ({ couponCode, discount }) => {
    const subject = 'Coupon Validated';
    const text = `Coupon ${couponCode} validated with ${discount}% discount.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
});

couponService.on('couponInvalid', async ({ couponCode }) => {
    const subject = 'Invalid Coupon';
    const text = `Coupon ${couponCode} is invalid.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
});

// SakshWishlistService Events
wishlistService.on('itemAddedToWishlist', async ({ userId, wishlistItem }) => {
    const subject = 'Item Added to Wishlist';
    const text = `User ${userId} added item ${wishlistItem.itemId} to their wishlist.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
    await sendEmail(getUserEmail(userId), subject, text); // Notify buyer
});

wishlistService.on('wishlistViewed', async ({ userId, items }) => {
    const subject = 'Wishlist Viewed';
    const text = `User ${userId} viewed their wishlist. Items: ${JSON.stringify(items)}`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
});

wishlistService.on('itemRemovedFromWishlist', async ({ userId, itemId }) => {
    const subject = 'Item Removed from Wishlist';
    const text = `User ${userId} removed item ${itemId} from their wishlist.`;
    
    await sendEmail(getUserEmail('admin'), subject, text); // Notify admin
    await sendEmail(getUserEmail(userId), subject, text); // Notify buyer
});

License

This project is licensed under the MIT License. See the LICENSE file for details.

Support

For support, please contact: [email protected]