Coursework Viva Generated 2026-05-27 Static HTML, ready to host

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

  1. 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.
  1. 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.
  1. 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.
  1. 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.
  1. Why use DTOs?
  • DTOs control request/response shape.
  • They avoid exposing full entity graphs.
  • They reduce over-posting risk and make validation easier.
  1. 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.
  1. What is a composite key in your project?
  • OrderItem uses { 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

  1. 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-only POST /api/users/register-staff.
  • Identity creates ApplicationUser.
  • Role is assigned with UserManager.AddToRoleAsync.
  • Email confirmation token is generated and emailed.
  1. Why require email confirmation?
  • Identity option SignIn.RequireConfirmedEmail = true.
  • Customer login is blocked until email is confirmed.
  • Prevents fake/invalid email accounts.
  1. 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.
  1. What claims are inside the JWT?
  • sub, email, jti, ClaimTypes.NameIdentifier, ClaimTypes.Name, and one ClaimTypes.Role per role.
  1. How is JWT validated?
  • Program.cs configures AddJwtBearer.
  • It validates issuer, audience, lifetime, and signing key.
  • Secret key comes from config.
  • ClockSkew = TimeSpan.Zero, so expiry is strict.
  1. What is authentication vs authorization?
  • Authentication answers “who are you?” using JWT.
  • Authorization answers “what can you access?” using roles like Admin, Staff, Customer.
  1. 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.
  • ProtectedRoute also checks client-side auth state and roles.
  1. 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.
  1. 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.
  1. 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

  1. 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/products and /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.
  1. 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 Customer row.
  1. 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.
  1. 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.
  1. How does customer view order history?
  • /api/orders/my-orders or /api/customers/me/history.
  • Only current customer’s orders are returned based on IdentityUserId.
  1. Can a customer download another customer’s invoice?
  • No.
  • /api/orders/{id}/invoice checks if user is Admin/Staff; otherwise it verifies the order belongs to current customer.
  1. 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.
  1. How do customer vehicles work?
  • /api/vehicles is 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.
  1. 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.
  1. 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

  1. 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.
  1. 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.
  1. 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.
  1. What is customer credit?
  • If payment method is Credit, amount is added to Customer.CreditBalance.
  • CreditIssuedAt and CreditDueAt are set.
  • Staff/Admin can record payment using /api/customers/{id}/credit-payment.
  • When balance becomes zero, related pending credit orders are marked Paid.
  1. Can Staff delete products or customers?
  • Staff can create/update/delete products through ProductsController because product CRUD allows Admin,Staff.
  • Customer update/delete is Admin-only; Staff can create and view/search customers.

6. Admin Workflow

  1. 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.
  1. How does Admin manage staff?
  • GET /api/users/staff returns Admin and Staff users.
  • POST /api/users/register-staff creates 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-role changes Admin/Staff role.
  • POST /api/users/toggle-status/{id} locks/unlocks account.
  1. How is self-demotion prevented?
  • If logged-in Admin tries to change own role away from Admin, backend rejects it.
  1. How does Admin add products?
  • POST /api/products creates 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}.
  1. 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.
  1. How does Admin restock inventory?
  • Admin creates purchase invoice through POST /api/purchases.
  • Backend validates vendor/products.
  • Creates Purchase and PurchaseItem rows.
  • Increases each product’s StockQty.
  • Purchase history is available through GET /api/purchases.
  1. How are vendors managed?
  • Public read endpoints list vendors.
  • Admin-only create/update/delete.
  • Vendor has many products and many purchases.
  1. 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

  1. How is stock reduced?
  • During Staff/Admin sale and Customer purchase, backend checks StockQty >= Quantity, then subtracts quantity.
  1. How is stock increased?
  • Admin purchase invoice adds purchase item quantities to product stock.
  1. How are low-stock alerts implemented?
  • Inline after sale/purchase when stock falls below 10.
  • Background LowStockMonitorService runs every 6 hours and notifies Admins.
  1. 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.
  1. How do product filters work?
  • /api/products accepts name, SKU, brand, min/max price, category.
  • Query is built with EF Core IQueryable.
  1. What is SKU?
  • Stock Keeping Unit, a unique-ish identifier for inventory tracking.

8. Payment Workflow Questions

  1. What payment methods exist?
  • Cash, Credit, Khalti, eSewa.
  1. 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 PaymentTransaction with 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.
  1. 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.
  1. Why keep PaymentTransaction table?
  • To track gateway state separately from order.
  • Supports retries/idempotency.
  • Preserves transaction IDs, amount, status, and timestamps.
  1. 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

  1. What creates notifications?
  • New customer order.
  • Staff sale.
  • Low stock.
  • Appointment booking/status updates.
  • Part requests/status updates.
  • Successful online payments.
  1. How are notifications delivered?
  • Stored in Notifications table.
  • Targeted by TargetUserId or TargetRole.
  • Frontend fetches /api/notifications/mine and unread count.
  1. 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.
  1. Why use background services?
  • Some tasks should run automatically without user request.
  • Examples: reminders, monitoring, alerts.
  1. How is invoice email sent?
  • OrdersController builds invoice HTML and sends through configured IEmailSender.
  • PDF invoice download uses InvoicePdf.Generate.
  • Email failure is best-effort and does not fail sale creation.

10. Frontend Questions

  1. 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.
  1. What is Navbar responsible for?
  • Role-aware navigation.
  • Theme toggle.
  • Cart icon for customers.
  • Notification bell for customers.
  • Profile dropdown and logout.
  • Mobile menu.
  1. What is React Query used for?
  • Fetching/caching server state.
  • Invalidating stale data after mutations.
  • Example: after sale, invalidates products, customers, reports, orders.
  1. What is CartContext?
  • Stores cart in localStorage.
  • Tracks quantity, subtotal, discount, total.
  • Prevents quantity from exceeding known stock.
  1. What is Axios interceptor?
  • Adds Authorization: Bearer <token> to requests.
  • Clears local auth data on 401.
  1. 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

FeatureAdminStaffCustomer
Login/JWTYesYesYes
Product browsingYesYesYes/Public
Product create/update/deleteYesYesNo
Purchase invoices/restockYesNoNo
Staff role managementYesNoNo
Vendor managementYesNoView only
Customer create/view/searchYesYesOwn profile only
Customer update/deleteYesNoOwn profile/delete
Create sale/invoiceYesYesNo
Customer self-orderNoNoYes
Online paymentNoNoYes
Appointments manageYesYesOwn booking
Part request manageYesYesOwn request
Financial reportsYesNoNo
Customer reportsYesYesNo

12. Important Code Knowledge Questions

  1. Why did OrdersController use 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.
  1. Why use Include and ThenInclude?
  • To load related data like orders with order items and products, customers with vehicles/appointments, purchases with vendor/admin/items.
  1. 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.
  1. Why does customer delete lock Identity user?
  • To revoke access while preserving safer identity handling.
  1. 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.
  1. How are uploaded images stored?
  • Backend validates image type/size.
  • Saves to wwwroot/uploads/profiles or wwwroot/uploads/products.
  • Stores relative URL in Customer/Product.
  • Deletes old local image best-effort.
  1. Why is payment amount verified?
  • To prevent tampering where a user pays less than order total.
  • Khalti verification compares expected paisa with gateway total.
  1. What is idempotency in payment verify?
  • If transaction already Completed, backend returns success instead of duplicating updates.
  1. Why use DateTime.UtcNow?
  • Consistent server timestamps independent of local timezone.
  1. What is the purpose of migrations?
  • Version database schema changes.
  • Keep DB synchronized with EF Core models.

13. Possible Weaknesses / Improvement Questions

  1. 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.
  1. 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.
  1. What could go wrong if payment succeeds but verification fails?
  • Order remains Pending.
  • Admin can reconcile using PaymentTransaction records and gateway transaction ID.
  1. What could go wrong with email?
  • SMTP failure.
  • Current design does not fail sale if invoice email fails.
  • Could use retry queue in production.
  1. 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

  1. 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")].
  1. A Staff user tries to create a purchase invoice. What happens?
  • Frontend staff dashboard does not expose purchase invoice feature.
  • Backend /api/purchases requires Admin, so Staff gets 403.
  1. A customer orders more stock than available. What happens?
  • Backend returns BadRequest with insufficient stock message.
  • Stock is not deducted.
  1. A customer selects Credit payment. What happens?
  • Order is Pending.
  • Customer CreditBalance increases.
  • Due date is set.
  • Staff/Admin later records credit payment; when fully paid, pending credit orders become Paid.
  1. 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.
  1. 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.
  1. Admin changes their own role to Staff. What happens?
  • Backend rejects self-demotion.
  1. 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

  1. Explain full login flow from frontend form to protected API call.
  2. Explain why JWT contains roles and how backend reads them.
  3. Explain difference between Admin, Staff, and Customer permissions.
  4. Explain customer onboarding and why IdentityUserId is nullable in Customer.
  5. Explain order creation for Staff sale vs Customer checkout.
  6. Explain stock deduction and low-stock notification.
  7. Explain purchase invoice and how it updates inventory.
  8. Explain credit balance and credit reminders.
  9. Explain Khalti/eSewa flow and why order status is Pending before verification.
  10. Explain invoice generation and email.
  11. Explain appointments and vehicle ownership validation.
  12. Explain part request lifecycle.
  13. Explain reports: revenue, cost, profit, top products, pending credits.
  14. Explain how frontend route protection works.
  15. Explain why backend authorization is still needed even with frontend middleware.
  16. Explain EF Core relationships and delete behavior.
  17. Explain why DTOs are used.
  18. Explain caching in product controller.
  19. Explain background services.
  20. 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 Bearer token 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:

  1. Where it starts: frontend page or user action.
  2. Which API endpoint is called: name the controller/action.
  3. What validation happens: auth, role, ownership, data, stock.
  4. What database tables change: Customer, Order, OrderItem, Product, PaymentTransaction, Notification, etc.
  5. What response/UI update happens: React Query invalidation, redirect, notification, invoice, report.
  6. What security protects it: JWT, roles, ownership checks, backend authorization.