Hello-Rider / VPIMS Viva Preparation
This project is a Vehicle Parts and Inventory Management System with three main user journeys: Admin, Staff, and Customer. The backend is ASP.NET Core Web API with Entity Framework Core, PostgreSQL, ASP.NET Identity, JWT authentication, role-based authorization, email services, payment gateway integration, file uploads, background workers, and reporting. The frontend is Next.js with React Query, Axios, middleware route guards, localStorage/cookie auth state, and role-specific dashboards.
1. One-Minute Project Introduction
Question: Explain your project.
Answer points:
- The system manages vehicle parts, inventory, customers, sales, service appointments, customer orders, online payments, reports, and staff/admin operations.
- Customers can register, confirm email, complete onboarding, shop for parts, place orders, pay by Cash/Credit/Khalti/eSewa, book appointments, manage vehicles, request unavailable parts, review products/services, view history, and download invoices.
- Staff can register customers, search customer records, view inventory, create sales/invoices, manage customer credit payments, and view operational reports.
- Admin has full control: staff/role management, inventory CRUD, vendor management, purchase invoices/restocking, financial reports, customer records, appointments, part requests, notifications, and security.
- Backend enforces authentication and authorization through Identity, JWT, and
[Authorize(Roles = "...")]. - Frontend enforces route-level access using Next.js middleware plus client-side guards.
2. Architecture Questions
- What architecture did you use?
- Client-server architecture.
- Frontend: Next.js/React.
- Backend: ASP.NET Core REST API.
- Database: PostgreSQL using EF Core.
- Authentication: ASP.NET Identity plus JWT.
- Why separate frontend and backend?
- Clear separation of UI and business logic.
- REST APIs can be consumed by web/mobile clients.
- Backend can enforce security independently of UI.
- What is the role of
Program.cs?
- Registers controllers, Swagger/OpenAPI, JWT settings, email settings, payment settings, memory cache, DbContext, Identity, CORS, static files, authentication, authorization, roles, and background services.
- What is
AppDbContext?
- EF Core database context.
- Inherits
IdentityDbContext<ApplicationUser>, so Identity tables and application tables share one database context. - Defines DbSets for Products, Customers, Orders, Purchases, Vehicles, Appointments, Notifications, Payments, etc.
- Why use DTOs?
- DTOs control request/response shape.
- They avoid exposing full entity graphs.
- They reduce over-posting risk and make validation easier.
- What is the database relationship structure?
- Category 1-M Products.
- Vendor 1-M Products.
- Customer 1-M Orders.
- Order 1-M OrderItems.
- Product 1-M OrderItems.
- ApplicationUser 1-M Purchases.
- Vendor 1-M Purchases.
- Purchase 1-M PurchaseItems.
- Customer 1-M Vehicles/Appointments/PartRequests/Reviews.
- Order 1-M PaymentTransactions.
- What is a composite key in your project?
OrderItemuses{ OrderId, ProductId }as a composite primary key because one order can contain many products and one product can appear in many orders.
3. Authentication and Authorization
- How does registration work?
- Customer registration calls
POST /api/auth/register-customer. - Admin/staff registration also exists in
AuthController, but real staff management uses Admin-onlyPOST /api/users/register-staff. - Identity creates
ApplicationUser. - Role is assigned with
UserManager.AddToRoleAsync. - Email confirmation token is generated and emailed.
- Why require email confirmation?
- Identity option
SignIn.RequireConfirmedEmail = true. - Customer login is blocked until email is confirmed.
- Prevents fake/invalid email accounts.
- How does login work?
- Frontend calls
POST /api/auth/login. - Backend finds user by email, checks lockout, validates password, resets failed count on success, checks customer email confirmation, reads roles, checks if customer profile exists, creates JWT, and returns token plus user object.
- What claims are inside the JWT?
sub, email,jti,ClaimTypes.NameIdentifier,ClaimTypes.Name, and oneClaimTypes.Roleper role.
- How is JWT validated?
Program.csconfiguresAddJwtBearer.- It validates issuer, audience, lifetime, and signing key.
- Secret key comes from config.
ClockSkew = TimeSpan.Zero, so expiry is strict.
- What is authentication vs authorization?
- Authentication answers “who are you?” using JWT.
- Authorization answers “what can you access?” using roles like Admin, Staff, Customer.
- How does frontend protect routes?
- Middleware reads cookies:
token,role,needsOnboarding. - It redirects unauthenticated users from dashboards, cart, checkout, account, orders, appointments.
- It prevents Staff from admin dashboard, Admin from staff dashboard, Customer from dashboards.
ProtectedRoutealso checks client-side auth state and roles.
- Why store token in both localStorage and cookies?
- Axios interceptor reads localStorage token to call API with
Authorization: Bearer. - Next.js middleware cannot read localStorage, so it uses cookies for route guarding.
- How is account lockout handled?
- Identity lockout is configured: 5 failed attempts locks account for 5 minutes.
- Staff/customer deletion or status toggle uses permanent lockout instead of physically deleting Identity access.
- What security risks should you mention honestly?
- CORS uses
AllowAnyOrigin, suitable for development but should be restricted in production. - JWT in localStorage can be vulnerable to XSS; hardened production could use HttpOnly secure cookies.
- Some Category endpoints lack role authorization, so they should be protected if only Admin/Staff should modify them.
4. Customer Workflow
- Customer registration to purchase flow
- Register on frontend.
- Confirm email using
/api/auth/confirm-email. - Login receives JWT and
needsOnboarding. - Complete onboarding via
/api/auth/complete-onboarding. - Browse products from
/api/productsand/api/products/with-details. - Add items to cart stored in
CartContext. - Checkout calls
/api/orders/customer-purchase. - Backend validates customer profile, products, stock, payment method, calculates discount, creates pending order, deducts stock, creates admin notification.
- If online payment, frontend starts Khalti/eSewa flow; verification marks order Paid.
- How does customer onboarding work?
- Backend gets current user ID/email from JWT claims.
- If an unlinked customer record matches email, phone, or normalized vehicle number, it links that record to the Identity user.
- Otherwise, it creates a new
Customerrow.
- How does customer purchase work?
- Endpoint:
POST /api/orders/customer-purchase. - Customer must be authenticated and have Customer role.
- It validates items, checks product existence and stock, deducts stock, calculates subtotal, applies 10% discount if subtotal > Rs. 5000, creates order with status Pending, and adds notification.
- Why do online orders start as Pending?
- Because the order is created before gateway verification.
- Payment verification from Khalti/eSewa changes status to Paid only after gateway lookup succeeds.
- How does customer view order history?
/api/orders/my-ordersor/api/customers/me/history.- Only current customer’s orders are returned based on
IdentityUserId.
- Can a customer download another customer’s invoice?
- No.
/api/orders/{id}/invoicechecks if user is Admin/Staff; otherwise it verifies the order belongs to current customer.
- How does customer appointment booking work?
- Customer calls
POST /api/appointments. - Backend resolves selected vehicle or latest vehicle.
- Creates appointment as Pending.
- Creates notification for customer and Admin.
- How do customer vehicles work?
/api/vehiclesis Customer-only.- Customer can create, update, list, delete own vehicles.
- Deleting a vehicle sets appointment vehicle reference to null due to
DeleteBehavior.SetNull, preserving history.
- How does part request work?
- Customer calls
POST /api/part-requests. - It can link to an existing product or be a free-text unavailable part request.
- Admin/Staff can approve or reject it.
- Customer receives notification.
- How does review system work?
- Customer posts
/api/reviews. - Product review checks product exists and prevents duplicate review per product per customer.
- General service review allows one general testimonial per customer.
- Reviews are publicly readable.
5. Staff Workflow
- What can Staff do?
- Access
/dashboard/staff. - Register customers.
- Search/view customers.
- View products/inventory.
- Create sales and invoices.
- View reports and customer credit information.
- Manage appointment and part request statuses where API allows Staff.
- How does Staff register a customer?
- Frontend uses customer hooks.
- Backend endpoint:
POST /api/customers. - It checks duplicate email/phone/vehicle number.
- If there is an Identity customer account without a profile, it links the new profile to that identity.
- How does Staff create a sale?
- Endpoint:
POST /api/orders/create-sale. - Roles: Staff or Admin.
- Validates customer and items.
- Checks product stock.
- Deducts stock.
- Applies 10% loyalty discount above Rs. 5000.
- Creates order.
- If payment method Credit, adds to customer credit balance and sets due date.
- Creates admin notification.
- Sends invoice email best-effort.
- Creates low-stock notifications/email if stock drops below 10.
- What is customer credit?
- If payment method is Credit, amount is added to
Customer.CreditBalance. CreditIssuedAtandCreditDueAtare set.- Staff/Admin can record payment using
/api/customers/{id}/credit-payment. - When balance becomes zero, related pending credit orders are marked Paid.
- Can Staff delete products or customers?
- Staff can create/update/delete products through
ProductsControllerbecause product CRUD allows Admin,Staff. - Customer update/delete is Admin-only; Staff can create and view/search customers.
6. Admin Workflow
- What can Admin do?
- Full dashboard access.
- Financial reports.
- Inventory CRUD.
- Purchase invoices/restocking.
- Staff and role management.
- Vendor management.
- Customer management.
- Appointments and part requests.
- Reports and notifications.
- Security actions like staff lock/unlock and role changes.
- How does Admin manage staff?
GET /api/users/staffreturns Admin and Staff users.POST /api/users/register-staffcreates Identity user with temp password, assigns Admin/Staff role, emails password setup link.PUT /api/users/update-staff/{id}updates profile names.PUT /api/users/change-rolechanges Admin/Staff role.POST /api/users/toggle-status/{id}locks/unlocks account.
- How is self-demotion prevented?
- If logged-in Admin tries to change own role away from Admin, backend rejects it.
- How does Admin add products?
POST /api/productscreates product with name, SKU, brand, price, stock, category, vendor.- Admin/Staff can create/update/delete.
- Cache is cleared after mutation.
- Product image can be uploaded through
/api/uploads/product/{id}.
- How does product delete work?
DELETE /api/products/{id}removes product and clears cache.- Relationships restrict deletion if product is referenced by order/purchase items; part requests/reviews linked to product use SetNull where configured.
- How does Admin restock inventory?
- Admin creates purchase invoice through
POST /api/purchases. - Backend validates vendor/products.
- Creates
PurchaseandPurchaseItemrows. - Increases each product’s
StockQty. - Purchase history is available through
GET /api/purchases.
- How are vendors managed?
- Public read endpoints list vendors.
- Admin-only create/update/delete.
- Vendor has many products and many purchases.
- How are reports generated?
- Financial report: paid order revenue, purchase cost, profit, order count, top products.
- Customer report: regulars, high spenders, pending credits.
- Sales report: paid orders, gross/net sales, discount, daily breakdown.
- Orders, stock, requested parts reports are filterable.
7. Product, Inventory, and Stock Questions
- How is stock reduced?
- During Staff/Admin sale and Customer purchase, backend checks
StockQty >= Quantity, then subtracts quantity.
- How is stock increased?
- Admin purchase invoice adds purchase item quantities to product stock.
- How are low-stock alerts implemented?
- Inline after sale/purchase when stock falls below 10.
- Background
LowStockMonitorServiceruns every 6 hours and notifies Admins.
- Why use memory cache in
ProductsController?
- To cache all unfiltered products for 5 minutes and individual product details.
- Cache is invalidated on create/update/delete.
- How do product filters work?
/api/productsaccepts name, SKU, brand, min/max price, category.- Query is built with EF Core
IQueryable.
- What is SKU?
- Stock Keeping Unit, a unique-ish identifier for inventory tracking.
8. Payment Workflow Questions
- What payment methods exist?
- Cash, Credit, Khalti, eSewa.
- How does Khalti payment work?
- Customer creates order with PaymentMethod Khalti.
- Frontend calls
/api/payments/khalti/initiate. - Backend verifies order belongs to current customer and is not paid.
- Backend calls Khalti service, stores
PaymentTransactionwith pidx. - Customer is redirected to gateway.
- Callback page verifies via
/api/payments/khalti/verify. - Backend looks up payment status, validates amount in paisa, marks transaction Completed and order Paid.
- How does eSewa payment work?
- Similar to Khalti.
- Backend creates signed payment form data.
- It stores transaction UUID as
Pidx. - Verification parses eSewa callback data or fallback transaction UUID.
- Successful lookup marks order Paid.
- Why keep
PaymentTransactiontable?
- To track gateway state separately from order.
- Supports retries/idempotency.
- Preserves transaction IDs, amount, status, and timestamps.
- How do you prevent paying someone else’s order?
- Payment initiation and verification check order/customer ownership against current JWT customer.
9. Notifications, Email, and Background Services
- What creates notifications?
- New customer order.
- Staff sale.
- Low stock.
- Appointment booking/status updates.
- Part requests/status updates.
- Successful online payments.
- How are notifications delivered?
- Stored in
Notificationstable. - Targeted by
TargetUserIdorTargetRole. - Frontend fetches
/api/notifications/mineand unread count.
- What background services exist?
LowStockMonitorService: every 6 hours.CreditReminderService: daily overdue credit reminders.ServiceReminderService: daily service reminder if last appointment is older than 6 months.
- Why use background services?
- Some tasks should run automatically without user request.
- Examples: reminders, monitoring, alerts.
- How is invoice email sent?
OrdersControllerbuilds invoice HTML and sends through configuredIEmailSender.- PDF invoice download uses
InvoicePdf.Generate. - Email failure is best-effort and does not fail sale creation.
10. Frontend Questions
- What is
LayoutManager?
- Wraps app with React Query provider, CartProvider, Toaster, Navbar/Footer visibility logic.
- Hides navbar/footer on login/register/onboarding and admin/staff dashboard pages.
- What is
Navbarresponsible for?
- Role-aware navigation.
- Theme toggle.
- Cart icon for customers.
- Notification bell for customers.
- Profile dropdown and logout.
- Mobile menu.
- What is React Query used for?
- Fetching/caching server state.
- Invalidating stale data after mutations.
- Example: after sale, invalidates products, customers, reports, orders.
- What is
CartContext?
- Stores cart in localStorage.
- Tracks quantity, subtotal, discount, total.
- Prevents quantity from exceeding known stock.
- What is Axios interceptor?
- Adds
Authorization: Bearer <token>to requests. - Clears local auth data on 401.
- Why use middleware and client checks both?
- Middleware blocks navigation before rendering.
- Client checks handle hydrated app state and extra redirection/toasts.
- Backend remains final security boundary.
11. Admin/Staff/Customer Role Comparison
| Feature | Admin | Staff | Customer |
|---|---|---|---|
| Login/JWT | Yes | Yes | Yes |
| Product browsing | Yes | Yes | Yes/Public |
| Product create/update/delete | Yes | Yes | No |
| Purchase invoices/restock | Yes | No | No |
| Staff role management | Yes | No | No |
| Vendor management | Yes | No | View only |
| Customer create/view/search | Yes | Yes | Own profile only |
| Customer update/delete | Yes | No | Own profile/delete |
| Create sale/invoice | Yes | Yes | No |
| Customer self-order | No | No | Yes |
| Online payment | No | No | Yes |
| Appointments manage | Yes | Yes | Own booking |
| Part request manage | Yes | Yes | Own request |
| Financial reports | Yes | No | No |
| Customer reports | Yes | Yes | No |
12. Important Code Knowledge Questions
- Why did
OrdersControlleruse controller-level[Authorize]but role attributes per action?
- If the controller had
[Authorize(Roles = "Admin,Staff")], adding[Authorize(Roles = "Customer")]on customer endpoints would require both, causing 403. Per-action roles avoid this.
- Why use
IncludeandThenInclude?
- To load related data like orders with order items and products, customers with vehicles/appointments, purchases with vendor/admin/items.
- What is
DeleteBehavior.Restrict,Cascade,SetNull?
- Restrict blocks delete if dependent data exists.
- Cascade deletes child data when parent deleted.
- SetNull preserves child history but removes relationship.
- Why does customer delete lock Identity user?
- To revoke access while preserving safer identity handling.
- What is
User.FindFirstValue(ClaimTypes.NameIdentifier)used for?
- To get current logged-in Identity user ID from JWT.
- Used to map Identity user to Customer record.
- How are uploaded images stored?
- Backend validates image type/size.
- Saves to
wwwroot/uploads/profilesorwwwroot/uploads/products. - Stores relative URL in Customer/Product.
- Deletes old local image best-effort.
- Why is payment amount verified?
- To prevent tampering where a user pays less than order total.
- Khalti verification compares expected paisa with gateway total.
- What is idempotency in payment verify?
- If transaction already Completed, backend returns success instead of duplicating updates.
- Why use
DateTime.UtcNow?
- Consistent server timestamps independent of local timezone.
- What is the purpose of migrations?
- Version database schema changes.
- Keep DB synchronized with EF Core models.
13. Possible Weaknesses / Improvement Questions
- What would you improve?
- Restrict CORS to frontend domain.
- Use HttpOnly secure cookies for JWT.
- Add stronger validation to Category CRUD and Product SKU uniqueness.
- Protect Category write endpoints with Admin/Staff authorization.
- Add database transactions around stock deduction/order creation/payment-critical flows.
- Add automated tests for auth, stock, payment, and role boundaries.
- Add pagination to product/customer lists.
- Use refresh tokens for longer sessions.
- What could go wrong in stock handling?
- Race condition: two users could buy last stock at same time.
- Improvement: use DB transaction/concurrency token/row lock.
- What could go wrong if payment succeeds but verification fails?
- Order remains Pending.
- Admin can reconcile using PaymentTransaction records and gateway transaction ID.
- What could go wrong with email?
- SMTP failure.
- Current design does not fail sale if invoice email fails.
- Could use retry queue in production.
- What testing would you do?
- Unit tests for discount/credit/status logic.
- Integration tests for endpoints and role authorization.
- Payment mock tests.
- UI tests for login, checkout, dashboard access.
14. Scenario Questions
- A customer tries to access
/dashboard/admin. What happens?
- Middleware sees Customer role and redirects to home with access denied.
- Backend APIs also reject Admin-only calls due to
[Authorize(Roles = "Admin")].
- A Staff user tries to create a purchase invoice. What happens?
- Frontend staff dashboard does not expose purchase invoice feature.
- Backend
/api/purchasesrequires Admin, so Staff gets 403.
- A customer orders more stock than available. What happens?
- Backend returns BadRequest with insufficient stock message.
- Stock is not deducted.
- A customer selects Credit payment. What happens?
- Order is Pending.
- Customer
CreditBalanceincreases. - Due date is set.
- Staff/Admin later records credit payment; when fully paid, pending credit orders become Paid.
- A product stock falls to 5 after sale. What happens?
- Sale completes.
- Admin notification is created.
- Admin low-stock email is attempted.
- Background monitor can also detect it later.
- A customer books an appointment for a vehicle they do not own. What happens?
- Backend checks vehicle belongs to current customer.
- Returns BadRequest if not owned.
- Admin changes their own role to Staff. What happens?
- Backend rejects self-demotion.
- User forgets password. What happens?
- Frontend calls forgot-password endpoint.
- Backend generates Identity password reset token, encodes it, emails set-password link.
- Reset endpoint decodes token and updates password.
15. Very Likely Viva Questions
- Explain full login flow from frontend form to protected API call.
- Explain why JWT contains roles and how backend reads them.
- Explain difference between Admin, Staff, and Customer permissions.
- Explain customer onboarding and why
IdentityUserIdis nullable in Customer. - Explain order creation for Staff sale vs Customer checkout.
- Explain stock deduction and low-stock notification.
- Explain purchase invoice and how it updates inventory.
- Explain credit balance and credit reminders.
- Explain Khalti/eSewa flow and why order status is Pending before verification.
- Explain invoice generation and email.
- Explain appointments and vehicle ownership validation.
- Explain part request lifecycle.
- Explain reports: revenue, cost, profit, top products, pending credits.
- Explain how frontend route protection works.
- Explain why backend authorization is still needed even with frontend middleware.
- Explain EF Core relationships and delete behavior.
- Explain why DTOs are used.
- Explain caching in product controller.
- Explain background services.
- Explain improvements and limitations.
16. Short Answers to Memorize
- Authentication: The user proves identity by logging in; backend issues a JWT.
- Authorization: Role-based
[Authorize]decides which API actions the authenticated user can access. - JWT: Signed token containing user identity and roles; sent as
Bearertoken in Authorization header. - Identity: Handles user creation, password hashing, roles, email confirmation, lockout, password reset.
- EF Core: ORM used to map C# models to PostgreSQL tables and manage relationships.
- DTO: Object used for API request/response instead of exposing database entity directly.
- Middleware: Frontend server-side route guard based on auth cookies.
- React Query: Caches API data and refreshes it after mutations.
- Stock flow: Sale/customer order reduces stock; admin purchase invoice increases stock.
- Payment flow: Order created pending; gateway verification marks Paid.
- Credit flow: Credit order increases customer balance; settlement reduces balance and can mark orders Paid.
- Notification flow: Events create Notification records targeted to user or role; frontend fetches them.
17. Final Confidence Script
If you get stuck, answer with this structure:
- Where it starts: frontend page or user action.
- Which API endpoint is called: name the controller/action.
- What validation happens: auth, role, ownership, data, stock.
- What database tables change: Customer, Order, OrderItem, Product, PaymentTransaction, Notification, etc.
- What response/UI update happens: React Query invalidation, redirect, notification, invoice, report.
- What security protects it: JWT, roles, ownership checks, backend authorization.