This Motoko backend is a comprehensive migration of the Django REST API backend for the Vendor Dapp. It replicates all Django models, business logic, API endpoints, and utilities as canister methods on the Internet Computer (ICP). The backend provides seamless compatibility with the existing frontend while leveraging ICP's decentralized infrastructure.
- main.mo: Main canister actor with all public endpoints and business logic
- models/: Modular data models with CRUD operations
Company.mo: Company management with public/private visibilityCategory.mo: Product categorization systemProduct.mo: Product inventory with pricing, tax rates, and status trackingRetailer.mo: Legacy retailer management for backward compatibilityRetailerProfile.mo: Modern retailer profiles with detailed business informationOrder.mo: Order management with items and status trackingOperations.mo: Employee, truck, and shipment managementBusiness.mo: Advanced business logic (invoices, connections, invites, user management)
- utils/: Utility modules for cross-cutting concerns
auth.mo: Authentication, session management, and authorizationemail.mo: Email notifications for OTP, invites, and status updatesallocation.mo: Order allocation algorithms and route optimizationodoo.mo: ERP integration with Odoo systems
- tests/: Test modules for canister functionality
- User: Principal-based identity with username, email, groups, and admin privileges
- AuthSession: Session management with expiration and role-based access
- PasswordResetOTP: OTP-based password recovery system
- Company: Multi-tenant company system with public visibility options
- Category: Hierarchical product categorization
- Product: Complete inventory management with:
- Quantity tracking (available, shipped, required)
- UQC (Unit of Quantity Code) support for all standard units
- Tax configuration (CGST, SGST, IGST, CESS rates)
- HSN code support for GST compliance
- Status tracking (sufficient/on_demand)
- Price management
- RetailerProfile: Comprehensive retailer business profiles
- Retailer: Legacy retailer entities linked to companies
- CompanyRetailerConnection: Many-to-many relationship management with:
- Connection status (pending, approved, rejected, suspended)
- Credit limits and payment terms
- Approval workflows
- CompanyInvite: Invitation system with unique codes and expiration
- RetailerRequest: Request-based company joining system
- Order: Complete order system with:
- Order items with product quantities
- Status tracking (pending, allocated, delivered, cancelled)
- Retailer association
- OrderItem: Individual line items within orders
- Employee: Staff management with company/retailer association and truck assignment
- Truck: Fleet management with capacity and availability tracking
- Shipment: Delivery management with employee assignment and status tracking
- Invoice: Complete invoicing system with:
- E-invoice support (IRN generation)
- Tax calculations (CGST, SGST, IGST)
- Payment tracking (cash, UPI, card, bank)
- Due date management
- InvoiceItem: Detailed line items with product-wise tax calculations
register(username, email, password, groups): User registration with role assignmentlogin(username, password): Authentication with session creationlogout(): Session terminationgetLoggedInUser(): Current user informationforgotPassword(username, email): Initiate password reset with OTPverifyOTP(username, otp): OTP verificationresetPassword(username, new_password, otp): Complete password reset
createCompany(...): Create new company with full detailsgetCompanies(): Retrieve user's companiesgetPublicCompanies(): Browse public companies (for retailers)updateCompany(id, ...): Update company informationdeleteCompany(id): Remove company
createCategory(company_id, name): Add product categorygetCategories(company_id?): Retrieve categories (filtered by company)updateCategory(id, name): Modify categorydeleteCategory(id): Remove categorygetCategoryStockData(): Analytics for category-wise product distribution
createProduct(...): Add products with complete tax and inventory detailsgetProducts(company_id?): Retrieve products (filtered by company)updateProductQuantity(id, available, shipped, required): Inventory updatesdeleteProduct(id): Remove productstoreQRCode(qr_text): QR code-based inventory updates (admin only)
createRetailerProfile(...): Self-registration for retailersgetRetailerProfile(): Retrieve current user's retailer profileupdateRetailerProfile(...): Update retailer business informationaddRetailer(...): Company adds retailer (legacy method)getRetailers(company_id?): Retrieve retailers
createOrder(retailer_id, items): Place new orders with multiple itemsgetOrders(status?): Retrieve orders (optionally filtered by status)getOrdersByRetailer(retailer_id): Retailer-specific order historyupdateOrderStatus(order_id, status): Order status updatesapproveOrder(order_id): Convert order to shipment (creates shipment record)
createEmployee(company_id, retailer_id?, contact, truck_id?): Add staffgetEmployees(company_id?): Retrieve employeescreateTruck(company_id, license_plate, capacity): Fleet management (admin only)getTrucks(company_id?): Retrieve trucksallocateOrder(order_id, employee_id): Manual order allocationgetShipments(): Retrieve all shipmentsgetEmployeeShipments(): Employee's assigned shipmentsupdateShipmentStatus(shipment_id, status): Update delivery status
createInvoice(...): Generate invoices with tax calculationsgetInvoices(company_id?): Retrieve invoicesgetInvoiceCount(company_id): Invoice statistics
requestCompanyApproval(company_id, message): Retailer requests to join companyacceptRetailerRequest(request_id, action, credit_limit, payment_terms): Company approves/rejects requestsgetCompanyConnections(company_id, status): Manage retailer relationships
getCounts(company_id): Dashboard statistics (orders, employees, retailers)getRetailerCounts(): Retailer dashboard statisticsgetCategoryStockData(): Product distribution analytics
health(): System health check
- Uses ICP Principal for user identification
- Session-based authentication with expiration
- Role-based access control (admin, employee, retailer)
- Admin: Full system access, can manage trucks, process QR codes
- Employee: Order allocation, shipment management, company operations
- Retailer: Profile management, order placement, company browsing
- Public: Company discovery, registration
- Password validation and hashing
- OTP-based password recovery
- Session expiration management
- Role-based method access control
| Django Model | Motoko Module | Key Features |
|---|---|---|
| User | Business.User | Principal-based identity |
| Company | Company.Company | Public/private visibility |
| Category | Category.Category | Company association |
| Product | Product.Product | Complete inventory + tax |
| Retailer | Retailer.Retailer | Legacy compatibility |
| RetailerProfile | RetailerProfile.RetailerProfile | Modern retailer system |
| Order/OrderItem | Order.Order/OrderItem | Items embedded in orders |
| Employee | Operations.Employee | User + company + truck |
| Truck | Operations.Truck | Fleet management |
| Shipment | Operations.Shipment | Delivery tracking |
| Invoice/InvoiceItem | Business.Invoice/InvoiceItem | Tax compliance |
| Django ViewSet | Motoko Methods | Functionality |
|---|---|---|
| CompanyViewSet | createCompany, getCompanies, updateCompany, deleteCompany | Full CRUD |
| CategoryViewSet | createCategory, getCategories, updateCategory, deleteCategory | Full CRUD |
| ProductViewSet | createProduct, getProducts, updateProductQuantity, deleteProduct | Inventory management |
| OrderViewSet | createOrder, getOrders, updateOrderStatus | Order lifecycle |
| InvoiceViewSet | createInvoice, getInvoices | Financial management |
| Django Endpoint | Motoko Method | Purpose |
|---|---|---|
| /register/ | register() | User registration |
| /token/ | login() | Authentication |
| /logout/ | logout() | Session termination |
| /forgot-password/ | forgotPassword() | Password recovery |
| /verify-otp/ | verifyOTP() | OTP validation |
| /reset-password/ | resetPassword() | Password reset |
| /approve_order/ | approveOrder() | Order approval |
| /allocate-order/ | allocateOrder() | Manual allocation |
| /category-stock/ | getCategoryStockData() | Analytics |
| /store_qr/ | storeQRCode() | QR processing |
| /count/ | getCounts() | Statistics |
- Order Lifecycle: pending → allocated → delivered/cancelled
- Inventory Management: Automatic quantity updates on shipment delivery
- Permission System: Role-based access control maintained
- Tax Compliance: HSN codes, GST rates, invoice generation
- Relationship Management: Company-retailer connections with approval workflows
- Allocation Logic: Employee assignment, truck capacity management
- DFX (DFINITY CLI) installed
- Motoko development environment
- Internet Computer network access
cd backend/motoko-backend
dfx start --background # Start local replica
dfx deploy # Deploy to local network
# For mainnet deployment:
dfx deploy --network ic# Call methods via DFX CLI
dfx canister call vendor_backend register '("username", "email@example.com", "password", vec {"employee"})'
# Get public companies
dfx canister call vendor_backend getPublicCompanies '()'
# Create company
dfx canister call vendor_backend createCompany '("Company Name", "GSTIN123", "Address", "State", "City", "123456", opt "phone", opt "email", true, opt "description")'The canister provides HTTP-compatible responses and can be integrated with the existing frontend through:
- Direct canister calls
- HTTP gateway integration
- Candid interface generation
- Decentralization: No single point of failure
- Scalability: Automatic scaling on ICP
- Cost Efficiency: Pay-per-use model
- Security: Built-in cryptographic security
- Persistence: Permanent data storage
- Global Access: Worldwide availability
- API Compatibility: All Django endpoints mapped to canister methods
- Data Integrity: All relationships and constraints preserved
- Business Logic: Complete feature parity
- Authentication: Enhanced with ICP identity system
- Define types in appropriate model modules
- Implement CRUD operations
- Add business logic in main canister
- Include authentication checks
- Add comprehensive error handling
# Run tests
dfx canister call vendor_backend_test runTests '()'- Use DFX logs for debugging
- Implement custom logging in canister methods
- Monitor canister cycles consumption
- Advanced Analytics: Real-time dashboards and reporting
- Mobile Integration: Direct mobile app connectivity
- Multi-Chain Support: Cross-chain asset management
- AI Integration: Predictive analytics and automation
- Advanced Security: Multi-signature approvals, audit trails
- Payment Systems: Direct crypto payments
- Supply Chain: Blockchain-based tracking
- Identity Systems: Decentralized identity verification
- IoT Integration: Real-time inventory tracking
This Motoko backend provides complete feature parity with the original Django system while adding the benefits of decentralized infrastructure. All business processes, data relationships, and API contracts are preserved, ensuring seamless migration with enhanced capabilities.