Comprehensive Guide to Building a Stock Management Backend

What is a Backend?

The backend is the part of your application that powers the frontend. It handles data storage, business logic, and communication with the database. In the context of a stock management system, the backend is responsible for managing products, tracking inventory, recording sales, and generating reports.

Core Components of a Backend

  1. Models:

    • Models represent your database structure in code.

    • They define the fields (columns) and relationships between the tables.

    • Example: A Product model may have attributes like name, price, and quantity_in_stock.

  2. Controllers (Ruby on Rails) / Views (Django):

    • The logic that processes incoming requests, interacts with the models, and prepares the data for the response.

    • Example: A ProductsController can handle adding a new product or fetching all products.

  3. Routes:

    • Define the URLs your backend listens to and maps them to specific controller actions or views.

    • Example: A route GET /products could map to a function that retrieves all products.


Database Design

We need a database to store and organize our stock management data. Below is an example schema:

1. Products

Tracks all the products your business manages.
Fields:

  • id: Primary key (auto-generated by the database).

  • name: The name of the product.

  • description: A detailed explanation of the product.

  • price: The cost of the product.

  • quantity_in_stock: How much stock is available.

  • timestamps: Automatic fields to track when a record is created or updated.

2. Suppliers

Stores information about suppliers.
Fields:

  • id: Primary key.

  • name: Supplier's name.

  • contact: Phone number.

  • email: Email address.

  • address: Physical location.

3. Orders

Tracks orders from suppliers.
Fields:

  • id: Primary key.

  • supplier_id: Foreign key linking to the supplier.

  • total_amount: Total value of the order.

  • timestamps: When the order was created or updated.

4. OrderDetails

Tracks the products included in each order.
Fields:

  • id: Primary key.

  • order_id: Foreign key linking to the order.

  • product_id: Foreign key linking to the product.

  • quantity: How many units of the product were ordered.

  • price: Price of each unit.

5. Sales

Tracks customer purchases.
Fields:

  • id: Primary key.

  • product_id: Foreign key linking to the product.

  • quantity: Number of items sold.

  • total_price: Total cost of the sale.

  • sale_date: When the sale occurred.


Backend Development

You can use either Ruby on Rails or Django. Let’s start with Ruby on Rails. All the commands are run in your terminal of Visual studio code


Part 1: Ruby on Rails Backend

Step 1: Set Up Rails

  1. Install Rails and PostgreSQL:

     gem install rails
     rails new stock_management --database=postgresql
     cd stock_management
    

    Rails automatically sets up a project structure with folders for models, controllers, and views.

  2. Database Configuration: Open config/database.yml and configure it for PostgreSQL. Then, create the database:

     rails db:create
    

Step 2: Create Models

What are Models?
Models define the structure of your database tables in Rails. Each model represents a single table.

Creating Models
Use Rails generators to create models:

rails g model Product name:string description:text price:decimal quantity_in_stock:integer
rails g model Supplier name:string contact:string email:string address:string
rails g model Order supplier:references total_amount:decimal
rails g model OrderDetail order:references product:references quantity:integer price:decimal
rails g model Sale product:references quantity:integer total_price:decimal sale_date:datetime

Run migrations to apply the changes:

rails db:migrate

Step 3: Add Controllers

What are Controllers?
Controllers handle incoming requests (e.g., adding a new product) and decide how to respond. They interact with models and send data to the frontend.

Creating Controllers
Generate controllers for each resource:

rails g controller Products
rails g controller Suppliers
rails g controller Orders
rails g controller Sales

Add logic to the controllers. For example, in products_controller.rb:

class ProductsController < ApplicationController
  def index
    @products = Product.all
    render json: @products
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      render json: @product, status: :created
    else
      render json: @product.errors, status: :unprocessable_entity
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, :description, :price, :quantity_in_stock)
  end
end

Step 4: Define Routes

What are Routes?
Routes define how URLs map to specific controller actions.

Add routes to config/routes.rb:

Rails.application.routes.draw do
  resources :products
  resources :suppliers
  resources :orders
  resources :sales
end

Step 5: Test and Run

  1. Start the server:

     rails server
    
  2. Test endpoints using Postman or a browser:

    • GET /products to fetch all products.

    • POST /products to add a product.


Part 2: Django Backend

Step 1: Set Up Django

  1. Install Django:

     pip install django
     django-admin startproject stock_management
     cd stock_management
    
  2. Start the server:

     python manage.py runserver
    

Step 2: Create Models

What are Models?
Models in Django are Python classes that map to database tables.

Define models in models.py:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity_in_stock = models.IntegerField()

class Supplier(models.Model):
    name = models.CharField(max_length=255)
    contact = models.CharField(max_length=50)
    email = models.EmailField()
    address = models.TextField()

class Order(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    total_amount = models.DecimalField(max_digits=10, decimal_places=2)

class OrderDetail(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)

class Sale(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    total_price = models.DecimalField(max_digits=10, decimal_places=2)
    sale_date = models.DateTimeField()

Run migrations:

python manage.py makemigrations
python manage.py migrate

Step 3: Add Views

What are Views?
Views define how data is presented. For APIs, views format data for the frontend.

Example in views.py:

from django.http import JsonResponse
from .models import Product

def product_list(request):
    products = list(Product.objects.values())
    return JsonResponse(products, safe=False)

Step 4: Define URLs

What are URLs?
URLs map routes to specific views.

Add routes in urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('products/', views.product_list),
]

Final Touches

  • Test APIs with Postman or a browser.

  • Deploy:

    • Rails: Use Heroku.

    • Django: Use PythonAnywhere or Heroku.

  • Enhance with authentication and reporting features.

Your stock management backend is now fully operational! 🎉