A full-stack wallet management system with Node.js backend and vanilla JavaScript frontend.
- β User Authentication (JWT-based)
- π° Wallet Balance Management
- π³ Payment Processing (P2P & Merchant)
- π Transaction History
- π« Reward Points System
- π Refund Management
- π Notifications
- π Audit Trail
- Node.js + Express
- MySQL with Stored Procedures
- JWT Authentication
- bcryptjs for password hashing
- Vanilla JavaScript
- Bootstrap 5
- Fetch API
- Node.js (v14+)
- MySQL (v8+)
- Git
First, create the database and tables:
# π¦ SmartWallet β Wallet Management System
This repository contains a full-stack wallet management system: a Node.js + Express backend connected to a MySQL database, and a lightweight vanilla-JavaScript frontend. The app supports P2P and merchant payments, rewards, refunds, notifications, profile management (including profile pictures), and analytics reports.
This README documents how to set up the project, what has been implemented, the database schema (tables, triggers, stored procedures, functions, and events), the API surface, and how to test features locally.
---
## π Quick overview
- Backend: Node.js + Express, MySQL (mysql2/promise), JWT-based auth
- Frontend: Static vanilla JavaScript pages in `wallet-frontend`
- Database: single-file DB schema and logic in `wallet_system_complete.sql` (tables, triggers, stored procedures, functions, and scheduled events)
---
## Table of contents
- Prerequisites
- Installation & setup
- Running the app
- Implemented features (what's done)
- Database schema (tables and purpose)
- Triggers, functions, stored procedures, events
- API endpoints (summary)
- Frontend pages
- Migration: ALTER TABLE to add profile picture column
- Troubleshooting
- Next steps & suggestions
---
## Prerequisites
- Node.js (v14+ recommended)
- MySQL (v8+ recommended) with privileges to create events/triggers/procedures
- Git
---
## Installation & setup
1. Clone the repo and open it:
```powershell
cd C:\Users\hario\coding\DBMS_PROJECT- Create the database schema (runs tables, triggers, procs, events):
mysql -u <db_user> -p < wallet_system_complete.sql- Configure the backend environment
Create a .env file inside wallet-backend/ with these variables (example):
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_db_password
DB_NAME=WalletSystem
PORT=5000
JWT_SECRET=change_this_to_a_strong_secret- Install backend dependencies and start the server:
cd wallet-backend
npm install
npm start- Serve the frontend (optional simple server):
cd wallet-frontend\main
# Option A: Python http server
python -m http.server 8000
# Option B: use VS Code Live Server or any static serverOpen http://localhost:8000 (or open the main HTML files directly) and login.
Note: backend runs on http://localhost:5000 by default and expects the frontend to call /api endpoints there.
This project implements the following features (major items):
-
Authentication and Account Management
- JWT-based login and registration
- Profile view & edit (including PIN rotation which requires the current PIN)
- Profile picture upload (server stores file and saves URL in DB)
-
Wallet & Payments
- User wallets and merchant wallets
- Payments (P2P and to merchants) using the
MakePaymentstored procedure (atomic) - Transaction history (includes incoming and outgoing payments and sender/receiver names)
-
Rewards
- Reward points awarded automatically when payments transition to Success (triggers)
- Redeem reward points endpoint which credits wallet and expires used rewards
-
Notifications
- Notification table and endpoints (Unread/Read) to inform users about payments/refunds
-
Refunds
- Refund request workflow: users create REFUND_TICKET; merchants receive notifications
- Merchant endpoints to approve/decline refunds; approval calls
ProcessRefundstored proc - Scheduled retry event to re-attempt refunds if merchant balance insufficient
-
Auditing & Ledger
- Wallet audit entries and wallet transactions ledger on balance changes
-
Analytics
- Monthly analysis report endpoints and a frontend
reports.htmlwith charts (daily trend, top counterparties) and CSV export
- Monthly analysis report endpoints and a frontend
The main tables created in wallet_system_complete.sql:
USERβ stores users (names, phone, email, address, password hash, wallet PIN hash, created_at)WALLETβ wallet balance per user (Wallet_ID, User_ID, Balance)MERCHANTβ merchants (Name, Business_Type, Email, Phn_No, Wallet_ID)PAYMENT_METHODβ payment methods (WALLET, UPI, CREDIT_CARD)PAYMENTβ payments ledger (Transaction_ID, User_ID (payer), Receiver_Type, Receiver_Entity_ID, Amount, Status, Transaction_Hash, Date_time)PAYMENT_HISTORYβ optional extended description per payment (Transaction_ID β Description)NOTIFICATIONβ user notifications (Notification_ID, User_ID, Message, Status)REFUND_TICKETβ refund requests (Refund_ID, Transaction_ID, Merchant_ID, Reason, Status, Attempts)REWARDSβ reward points rows for users (Reward_ID, User_ID, Points, Expiry_Date, Is_Expired)WALLET_AUDITβ audit trail of balance changes (Audit_ID, Wallet_ID, Old_Balance, New_Balance, Change_Type)WALLET_TRANSACTIONSβ ledger entries for wallet debits/credits (Txn_ID, Wallet_ID, Txn_Type, Amount, Remarks)
Indexes are defined for common queries (payment user/receiver indexes, indexes for refunds and rewards).
This project uses several DB-level automation pieces (in wallet_system_complete.sql):
-
Functions
GetTotalSpendByUser(p_user_id)β returns total successful spend for a user.GetUserRewardPoints(p_user_id)β returns total non-expired reward points for a user.
-
Triggers
WalletBalanceAuditβ BEFORE UPDATE onWALLETinserts a row intoWALLET_AUDITwhen balance changes.AfterPaymentAddRewardβ AFTER INSERT onPAYMENTadds a reward when Status = 'Success'.AfterPaymentUpdateAddRewardβ AFTER UPDATE onPAYMENTawards rewards when status transitions to 'Success' (handles updates from Pending to Success).
-
Stored Procedures
MakePayment(p_from_user_id, p_receiver_type, p_receiver_entity_id, p_amount, p_txn_hash, p_description)β core payment procedure; performs wallet balance updates, ledger entries and returns status (Success/Failed/ALREADY_EXISTS). It includes idempotency via Transaction_Hash.ProcessRefund(p_refund_id)β processes an existing refund ticket by attempting to debit the merchant wallet and credit the user's wallet; updatesREFUND_TICKETstatus accordingly.CreateRefundTicketAndProcess(p_transaction_id, p_merchant_id, p_reason)β creates a refund ticket then triggersProcessRefundfor immediate processing.
-
Scheduled Events
ExpireRewardsEventβ daily job to mark expired rewards.RetryPendingRefundsEventβ hourly job that retries processing refunds with limited attempts.
These DB-level constructs allow financial operations to be atomic and auditable.
Authentication
POST /api/auth/loginβ login, returns JWT tokenPOST /api/auth/registerβ register (supports merchant registration fields)GET /api/auth/profileβ get current user's profile (protected)PUT /api/auth/profileβ update profile (protected)POST /api/auth/profile/pictureβ upload profile picture (protected; multipart/form-datapicturefield)
Payments & Wallet (protected routes)
GET /api/payments/dashboardβ wallet info, ledger, history, rewards summaryGET /api/payments/contactsβ list users & merchants for quick sendPOST /api/paymentsβ make a payment (body: receiverType, receiverId, amount, pin, txnHash, description)GET /api/payments/:idβ get payment details
Rewards
GET /api/payments/rewardsβ list rewards & total pointsPOST /api/payments/rewards/redeemβ redeem available points into wallet
Refunds & Merchant actions
POST /api/payments/refundβ request a refund (creates REFUND_TICKET)GET /api/refunds/merchantβ merchant: list refund tickets for merchant(s) owned by userPOST /api/refunds/:id/approveβ merchant approves refund (callsProcessRefund)POST /api/refunds/:id/declineβ merchant declines refund
Notifications
GET /api/notificationsβ (not shown in detail here) list notifications for user
Reports
GET /api/reports/monthlyβ monthly analysis JSON (user by default; supportstype=merchant&merchantId=with authorization check)GET /api/reports/monthly/csvβ CSV export for user monthly report
All protected routes expect an Authorization: Bearer <token> header with a valid JWT.
wallet-frontend/main/index.htmlβ Dashboardwallet-frontend/main/login.htmlβ Login pagewallet-frontend/main/profile.htmlβ Profile view/edit (with profile picture upload)wallet-frontend/main/reports.htmlβ Monthly reports UI (charts + CSV export)wallet-frontend/main/history.htmlβ Transaction historywallet-frontend/main/send.htmlβ Send funds to a userwallet-frontend/main/pay-merchant.htmlβ Pay merchant flow
Main JS files live in wallet-frontend/js/ and manage API calls and UI interactions.
If your database doesn't have the Profile_Pic column in USER, run this ALTER:
ALTER TABLE `USER`
ADD COLUMN `Profile_Pic` VARCHAR(255) NULL;Optional: place it after Address:
ALTER TABLE `USER`
ADD COLUMN `Profile_Pic` VARCHAR(255) NULL
AFTER `Address`;Rollback (remove column):
ALTER TABLE `USER` DROP COLUMN `Profile_Pic`;Notes: the backend expects Profile_Pic to contain a path like /uploads/user-<id>-<ts>.png. The server serves uploaded images from /uploads.
- Register or run
sampleSignup()(one-time helper) to seed a test user. - Login via frontend to get JWT stored in
localStorage.walletToken. - Make a payment from the Send UI (provide correct 6-digit PIN).
- Check dashboard and history β incoming payments should be visible for recipients.
- Request a refund from the transaction detail; check merchant's
refundsUI (merchant must be registered and matched to a user account to approve). - Redeem rewards from the Rewards page; check wallet balance updates.
- Visit Reports β load monthly report; download CSV.
- 404 Cannot GET /api/reports/monthly: ensure backend is running and that routes are registered. Restart backend and check logs.
- 401 Unauthorized: token missing or expired β log in again to get a fresh JWT.
- Database errors: check
.envDB connection values and thatWalletSystemschema was imported. - Event scheduler: to enable scheduled events run
SET GLOBAL event_scheduler = ON;as a user with SUPER privileges.
If something fails, check the backend console log (where npm start runs) for stack traces β controllers log errors with context.
This README reflects the features implemented in this workspace. Major changes include:
-
Backend
src/controllers/paymentController.jsβ payments, dashboard (incoming + outgoing history), rewards endpoints, redeem logicsrc/controllers/authController.jsβ register/login, profile GET/PUT, upload picture handler (multer)src/controllers/refundController.jsβ merchant refund listing, approve/decline endpointssrc/controllers/reportsController.jsβ monthly JSON and CSV report endpointssrc/routes/*β routes for auth, payments, refunds, notifications, and newreportsRoutes.jssrc/index.jsβ route registration and a debug helper for routes
-
Frontend
wallet-frontend/main/reports.html+wallet-frontend/js/reports.jsβ monthly reports UI and CSV downloadwallet-frontend/main/profile.html+wallet-frontend/js/profile.jsβ profile page and client-side upload/preview logicwallet-frontend/js/app.jsβ dashboard wiring (avatar, profile link, reports button)
-
Database
wallet_system_complete.sqlβ schema, triggers, stored procedures, functions, and scheduled events. (IncludesMakePayment,ProcessRefund, reward triggers, audit triggers, and scheduled events.)
If you need a changelog-style per-commit attribution, we can generate one from Git history.
- Merchant ownership mapping table (
MERCHANT_USER) to handle merchant permissions robustly (instead of simple email/phone match). - Server-side image resizing + validation for profile pictures.
- Background worker to produce PDF reports and email them (opt-in scheduled reports).
- Auto-categorization of transactions and budgeting features for users.
- Unit/integration tests for stored procedures and endpoints.
If you'd like me to add an OpenAPI spec, structured migration files, or implement any of the next improvements above, tell me which item to start with and I will implement it next.
Β© Project β Educational use