Skip to content

Feat/review sellers#154

Open
BrandonRodzz wants to merge 1 commit intoStarShopCr:Developfrom
BrandonRodzz:Feat/review-sellers
Open

Feat/review sellers#154
BrandonRodzz wants to merge 1 commit intoStarShopCr:Developfrom
BrandonRodzz:Feat/review-sellers

Conversation

@BrandonRodzz
Copy link

@BrandonRodzz BrandonRodzz commented Sep 5, 2025

🚀 StarShop Pull Request

Mark with an x all the checkboxes that apply (like [x])

  • Closes #
  • Added tests (if necessary)
  • Run tests
  • Run formatting
  • Evidence attached
  • Commented the code

📌 Type of Change

  • Documentation (updates to README, docs, or comments)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

📝 Changes description

🎯 Review & Rating System for Sellers

Implemented a comprehensive review and rating system that allows buyers to rate and review sellers after confirming a purchase. This builds trust and helps future buyers make informed decisions.

��️ Core Components Added

New Entity:

  • SellerReview entity with UUID primary key, foreign keys to offers and users, rating validation (1-5), and unique constraint for one review per offer

Updated Entity:

  • Enhanced User entity with averageSellerRating and totalSellerReviews fields for automatic rating aggregation

API Endpoints:

  • POST /api/v1/reviews - Create a new seller review
  • GET /api/v1/users/:id/reviews - Get all reviews for a specific seller
  • PUT /api/v1/reviews/:id - Update an existing review
  • DELETE /api/v1/reviews/:id - Delete a review

Business Logic:

  • SellerReviewService with comprehensive validation and business rules
  • SellerReviewController with NestJS decorators and JWT authentication
  • Validation middleware with class-validator decorators

Database:

  • Migration file to create seller_reviews table with proper constraints
  • Added seller rating columns to users table
  • Performance indexes and foreign key constraints

Business Rules Implemented

  • ✅ One review per offer (enforced by unique database constraint)
  • ✅ Only the buyer who confirmed the purchase can review
  • ✅ Rating must be between 1-5 stars (validation + database constraint)
  • ✅ Reviews only allowed for purchased offers (wasPurchased = true)
  • ✅ Users can only modify their own reviews
  • ✅ Automatic seller rating aggregation and caching

�� Testing Coverage

  • Unit Tests: Service and controller logic with comprehensive mocking
  • Integration Tests: End-to-end API testing with in-memory database
  • Validation Tests: Input validation and error handling scenarios

📚 Documentation

  • Comprehensive README with API documentation and usage examples
  • Inline code comments and JSDoc documentation
  • Database schema documentation

📸 Evidence (A photo is required as evidence)

API Endpoint Testing:

POST /api/v1/reviews
{
  "offerId": "offer-uuid",
  "rating": 5,
  "comment": "Excellent seller! Very professional and responsive."
}

Response: 201 Created
{
  "success": true,
  "data": {
    "id": "review-uuid",
    "offerId": "offer-uuid",
    "buyerId": "buyer-uuid",
    "rating": 5,
    "comment": "Excellent seller!",
    "createdAt": "2024-01-15T10:30:00Z",
    "buyer": { "id": "buyer-uuid", "name": "John Doe" },
    "offer": { "id": "offer-uuid", "title": "Custom Product", "price": 100 }
  }
}

Seller Reviews Endpoint:

GET /api/v1/users/seller-uuid/reviews

Response: 200 OK
{
  "success": true,
  "data": {
    "reviews": [...],
    "averageRating": 4.5,
    "totalReviews": 10,
    "seller": {
      "id": "seller-uuid",
      "name": "Jane Smith",
      "averageSellerRating": 4.5,
      "totalSellerReviews": 10
    }
  }
}

⏰ Time spent breakdown

  • Planning & Analysis: 30 minutes

    • Understanding existing codebase structure
    • Analyzing requirements and business rules
    • Designing database schema and API structure
  • Core Implementation: 2 hours

    • Creating SellerReview entity and DTOs
    • Implementing business logic service
    • Building API controller with NestJS decorators
    • Adding validation middleware
  • Database & Migration: 45 minutes

    • Creating database migration
    • Updating User entity
    • Adding proper constraints and indexes
  • Testing: 1.5 hours

    • Writing comprehensive unit tests
    • Creating integration tests
    • Testing edge cases and error scenarios
  • Documentation & Cleanup: 30 minutes

    • Writing comprehensive README
    • Adding inline documentation
    • Code formatting and linting

Total Time: ~5 hours


🌌 Comments

This implementation provides a robust foundation for the seller review system that can be easily extended in the future. The code follows NestJS best practices and includes comprehensive error handling, validation, and testing.

Key Features:

  • Scalable Architecture: Clean separation of concerns with services, controllers, and entities
  • Data Integrity: Database constraints ensure data consistency
  • Performance Optimized: Proper indexing and rating aggregation caching
  • Security: JWT authentication and ownership validation
  • Maintainable: Well-documented code with comprehensive test coverage

Future Enhancements:

  • Review moderation system
  • Review analytics and reporting
  • Email notifications for new reviews
  • Review response system for sellers

The implementation is production-ready and follows all the specified requirements while maintaining code quality and best practices.


Thank you for contributing to StarShop, we are glad that you have chosen us as your project of choice and we hope that you continue to contribute to this great project, so that together we can make our mark at the top!

Summary by CodeRabbit

  • New Features

    • Health endpoints: /api/v1/health/live and /ready with IP allowlist and memory/disk thresholds.
    • Stores: create/manage/search stores; default store auto-created for sellers.
    • Seller Reviews: buyers review sellers; ratings aggregated on seller profiles.
    • Offers: auto-expire after 7 days, admin/manual expiration, expiring-soon lookup, and offer status notifications.
    • Auth & Users: cookie-based JWT, walletAddress as primary ID, added user fields (location, country, buyerData/sellerData) with role-based validation.
  • Documentation

    • New/updated guides for health checks, user registration, technical spec, UUID migration, store system, offer auto-expiration, seller reviews, and README.
  • Configuration

    • Added env template and health-check env variables.

@coderabbitai
Copy link

coderabbitai bot commented Sep 5, 2025

Caution

Review failed

Failed to post review comments.

Walkthrough

Adds HealthModule with allowlisted liveness/readiness endpoints; introduces cookie-based JWT extraction/config; migrates user IDs to UUID and shifts APIs to walletAddress; adds role-specific user fields; creates Stores module; expands Offers with product linking, expiration cron/endpoints, and notifications; implements Seller Reviews module; updates entities, DTOs, migrations, tests, and documentation accordingly.

Changes

Cohort / File(s) Summary
Env & Ignore Templates
env.example, .env.example, .gitignore
Adds comprehensive env template including health vars; updates example with health section; ignores IMPLEMENTATION_*.md patterns.
Docs
README.md, docs/*, src/modules/reviews/README.md
Adds health checks docs, extensive specs for registration, UUID migration, store system, offers auto-expiration, technical spec, and seller reviews.
Config & Bootstrap
src/app.module.ts, src/config/index.ts, src/config/jwt.ts, src/main.ts
Registers Stores, Reviews, Health modules; toggles TypeORM sync (app: false, config: true); adds JWT cookie config helpers; enables cookie-parser.
Health Feature
src/health/*, src/middleware/healthAllowlist.guard.ts, package.json
Introduces health controller/module with liveness/readiness checks (DB, Redis, memory, disk) and allowlist guard; adds @nestjs/terminus and ip-range-check deps.
Auth & JWT Flow
`src/modules/auth/**/*(controller
service
Users Module
src/modules/users/**/*
Switches primary key to UUID; indexes walletAddress; adds new user fields; services/controllers use walletAddress; adds stores relation; updates response shapes and helper methods.
Stores Module
src/modules/stores/*, src/modules/auth/auth.module.ts
Adds Store entity, DTOs, controller, service, and module; integrates with AuthService to create default store for sellers.
Offers: Expiration, Product Linking, Admin
`src/modules/offers/**/*(controller
service
Notifications Enhancements
src/modules/notifications/*, src/migrations/1755667533000-AddOfferNotificationTypes.ts
Adds new types (offer_accepted/rejected), payload/entityId fields, repository wiring, JWT module import, and service methods including createAndSendNotificationToUser and pagination.
Seller Reviews Feature
`src/modules/reviews/**/*(entity
dto
Buyer Requests UUID Alignment
src/modules/buyer-requests/*
Changes userId types from number to UUID in entity, DTO, and service method signatures.
Migrations: UUID & Stores & FKs
src/migrations/1751199237000-*.ts, src/migrations/1751199238000-*.ts
Migrates users.id to UUID; adds user fields; creates stores table; updates related foreign keys to UUID; adds notifications enum/index changes.
Tests & Jest Setup
test/*, src/modules/files/tests/*, src/modules/offers/tests/*, src/modules/reviews/tests/*, src/modules/users/tests/*, test/jest-e2e.json
Updates fixtures for new user fields/UUIDs; adds multer mocks; config changes; adds new suites for offers expiration/notifications and seller reviews; adjusts auth e2e for cookies.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant API as API Gateway
  participant HC as HealthController
  participant DB as TypeORM DB
  participant RD as Redis (optional)
  participant OS as Disk/Memory

  Client->>API: GET /api/v1/health/live
  API->>HC: checkLive()
  HC-->>API: { status: "up" }
  API-->>Client: 200

  Client->>API: GET /api/v1/health/ready
  API->>HC: checkReady()
  HC->>DB: pingCheck(database)
  alt REDIS configured
    HC->>RD: connect + PING
    RD-->>HC: PONG
  end
  HC->>OS: memoryHeapCheck (if env)
  HC->>OS: diskStorageCheck (if env)
  HC-->>API: aggregated result
  API-->>Client: 200/503
Loading
sequenceDiagram
  autonumber
  participant Cron as OfferExpirationService (Cron)
  participant OfferSvc as OfferService
  participant Repo as OfferRepository
  participant Notif as NotificationService

  Cron->>OfferSvc: expireOffers()
  OfferSvc->>Repo: find({ status: PENDING, expiresAt < now })
  Repo-->>OfferSvc: [expiredOffers]
  alt Any expired
    loop each expired offer
      OfferSvc->>Repo: update(status=REJECTED, updatedAt=now)
      OfferSvc->>Notif: createAndSendNotificationToUser({ type: offer_rejected, entityId: offer.id, userId: sellerId, payload })
    end
  else None
    Note over OfferSvc: No-op
  end
  OfferSvc-->>Cron: expiredCount
Loading
sequenceDiagram
  autonumber
  actor Buyer
  participant API as API (JWT cookie)
  participant SRC as SellerReviewController
  participant Svc as SellerReviewService
  participant DB as Repos (Offer/User/SellerReview)
  participant User as User (Seller)

  Buyer->>API: POST /api/v1/reviews { offerId, rating, comment }
  API->>SRC: createReview(req.user.id, dto)
  SRC->>Svc: createReview(buyerId, dto)
  Svc->>DB: findOne(Offer with seller & buyerRequest)
  Svc->>DB: findOne(User as buyer)
  Svc->>DB: findOne(SellerReview by offerId+buyerId)
  alt Valid and not reviewed
    Svc->>DB: save(SellerReview)
    Svc->>DB: compute seller average + total
    Svc->>User: update(avg, total)
    Svc-->>SRC: SellerReviewResponseDTO
    SRC-->>API: 201 { success, data }
  else Error
    Svc-->>SRC: throws (NotFound/Forbidden/BadRequest)
    SRC-->>API: 4xx
  end
Loading
sequenceDiagram
  autonumber
  actor Client
  participant API as API
  participant JWT as JwtStrategy
  participant Auth as AuthService
  participant User as UserService

  Client->>API: Request with Cookie auth_token=JWT
  API->>JWT: extract from cookie/header
  JWT->>Auth: validate(payload)
  alt payload.walletAddress
    Auth->>User: getUserByWalletAddress()
  else payload.id
    Auth->>User: getUserById()
  end
  User-->>Auth: user
  Auth-->>JWT: user info
  JWT-->>API: req.user populated (UUID id)
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related issues

Possibly related PRs

  • Feat/health module #152 — Adds HealthModule, allowlist guard, env vars, and health docs matching the health checks introduced here.
  • Feat/auto expire offers #144 — Implements offer auto-expiration with expires_at, cron service, endpoints, and tests, overlapping with the offers expiration feature in this PR.
  • Feature/offer notifications #145 — Extends notifications with offer_accepted/rejected types and wires offer lifecycle notifications similar to this PR’s notification changes.

Suggested reviewers

  • Villarley

Poem

A rabbit taps deploy at night,
Cron clocks hum with gentle light.
UUIDs hop in tidy rows,
Health checks whisper status prose.
Stores sprout, reviews take flight—
Offers snooze, then fade from sight.
Ship it swift—ears up, code right! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Villarley Villarley changed the base branch from main to Develop September 5, 2025 04:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant