Team Task Division: Migrating to SC 12th December Version

This document divides all the changes needed to replicate the SC 12th December version into 3 logical, balanced tasks for the backend team members.


📋 Task Overview

Each team member will work on a complete, self-contained feature area that can be developed and tested independently. All tasks should be completed and pushed to the main branch.


👤 TASK 1: Swap Request System

Assigned to: Team Member 1

Overview

Implement the complete swap request system - backend service, API endpoints, and frontend components for managing swap requests.

Backend Work

1.1 Create Swap Service

    • Copy from SC 12th December version
    • Functions needed:
      • create_swap_request()
      • get_swap_request()
      • get_pending_requests_for_item()
      • get_pending_requests_for_owner()
      • get_requests_for_requester()
      • get_approved_swaps_for_user()
      • update_swap_request()
      • cancel_other_pending_requests()
    • Uses Backend/data/swap_requests.json for storage

1.2 Create Data File

    • Initialize as empty array: []

1.3 Add Swap Endpoints to Item Routes

    • Add import: from services import swap_service
    • Add new endpoint: GET /items/swap-requests
      • Returns swap requests for authenticated user (as owner and as requester)
      • Requires authentication
      • Enriches requests with item and user information
    • Add new endpoint: GET /items/swap-history
      • Returns approved swaps for authenticated user
      • Requires authentication
      • Enriches swaps with item and user information
    • Add new endpoint: POST /items/{item_id}/swap
      • Creates a swap request for an item
      • Prevents users from swapping their own items
      • Checks if item is available
      • Validates user has enough credits
      • Parses credits from item description
      • Marks item as “pending”
    • Add new endpoint: POST /items/{item_id}/swap/{request_id}/approve
      • Approves a swap request (owner only)
      • Transfers credits from requester to owner
      • Cancels other pending requests for the item
      • Marks item as “swapped”
    • Add new endpoint: POST /items/{item_id}/swap/{request_id}/reject
      • Rejects a swap request (owner only)
      • Updates item status back to “available” if no other pending requests
    • Update existing endpoints:
      • GET /items/ - Check for pending requests and update status to “pending” if needed
      • GET /items/{item_id} - Check for pending requests and update status to “pending” if needed
    • Update import paths: Change Backend.services to services (relative imports)

Frontend Work

1.4 Create Swap Components

    • Copy from SC 12th December version
    • Displays swap requests as owner (need approval) and as requester (my requests)
    • Handles approve/reject actions
    • Uses itemsAPI.getSwapRequests(), approveSwapRequest(), rejectSwapRequest()
    • Copy from SC 12th December version
    • Displays user’s swap history (completed swaps)
    • Shows approved swaps with item details
    • Uses itemsAPI.getSwapHistory()

1.5 Update API Service

    • Add new methods to itemsAPI:
      • requestSwap(itemId) - Request a swap for an item
      • approveSwapRequest(itemId, requestId) - Approve a swap request
      • rejectSwapRequest(itemId, requestId) - Reject a swap request
      • getSwapRequests() - Get swap requests for user
      • getSwapHistory() - Get swap history for user

1.6 Update Profile Component

    • Add “Swap Requests” tab (shows SwapRequests component)
    • Update “Swap History” tab to show SwapHistory component
    • Import and use SwapRequests and SwapHistory components
    • Fetch swap history using itemsAPI.getSwapHistory()

Testing Checklist


👤 TASK 2: Credit & Transaction System

Assigned to: Team Member 2

Overview

Enhance the credit system with transaction tracking, automatic credit awards, and improved performance.

Backend Work

2.1 Create Transaction Data File

    • Initialize as empty array: []

2.2 Update Credit Service

    • Update add_credits() function:
      • Add parameters: transaction_type (default “credit_add”) and description (optional)
      • Directly update user’s credits field using update_user() (O(1) instead of O(n))
      • Record transaction with the provided type and description
      • Import: from services.user_service import get_user_by_id, update_user
    • Update deduct_credits() function:
      • Directly update user’s credits field using update_user() (for performance)
      • Record transaction for audit trail
      • Import: from services.user_service import get_user_by_id, update_user
    • Update get_user_balance() function:
      • Add “item_upload” to credit types that add to balance
      • Change: if transaction.get("type") in ["credit_add", "swap_credit", "item_upload"]:
    • Add new function: sync_user_credits_from_transactions(user_id)
      • Recalculates and updates user’s credits from all transactions
      • Useful for data integrity checks
    • Update import paths: Change Backend.services.user_service to services.user_service

2.3 Add Credit Awarding to Item Creation

    • In create_item() endpoint, after successfully creating the item:
      • Add code to award 2 credits to the user
      • Use: credit_service.add_credits(user_id=owner_id, amount=2.0, transaction_type="item_upload", description=f"Credits awarded for uploading item: {item.title}")
      • Wrap in try-except to not fail item creation if credit awarding fails
      • Add import: from services import credit_service

2.4 Update Lock/Unlock Endpoints

    • Update lock_item() endpoint:
      • Add authentication requirement
      • Prevent users from locking their own items
      • Add check: if item_owner_id and item_owner_id == user_id: raise HTTPException(403, "You cannot swap or purchase your own items")
    • Update unlock_item() endpoint:
      • Add authentication requirement
      • Only allow owner to unlock their own items
      • Add check: if item_owner_id and item_owner_id != user_id: raise HTTPException(403, "Only the item owner can unlock this item")

Frontend Work

2.5 Update Profile Component (Credit Display)

    • Ensure credits are displayed correctly from user data
    • Credits should come from userAPI.getUser() response
    • Verify credits update after item upload

Testing Checklist


👤 TASK 3: Core Infrastructure & Integration

Assigned to: Team Member 3

Overview

Update core infrastructure (error handling, imports), improve API integration, and add utility functions.

Backend Work

3.1 Update Main Application File

    • Add validation error handler:
      • Import: from fastapi import Request, status
      • Import: from fastapi.exceptions import RequestValidationError
      • Import: from fastapi.responses import JSONResponse
      • Import: from pydantic import ValidationError
      • Add @app.exception_handler(RequestValidationError) decorator
      • Implement validation_exception_handler() function
      • Provides detailed error messages for validation errors
    • Update import paths to relative:
      • Change: from Backend.database.connection → from database.connection
      • Change: from Backend.routes.item_routes → from routes.item_routes
      • Change: from Backend.routes.auth_routes → from routes.auth_routes
      • Change: from Backend.routes.user_routes → from routes.user_routes
    • Improve static file mounting:
      • Use absolute path: ROOT = Path(__file__).resolve().parent
      • Use: STATIC_DIR = ROOT / "static"
      • Mount: app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
      • Import: from pathlib import Path

3.2 Update Item Routes (Error Handling & Multipart)

    • Improve create_item() endpoint:
      • Better multipart/form-data handling
      • Improved error messages for validation errors
      • Handle both JSON and multipart requests
      • Better error formatting using ValidationError
    • Update import paths to relative:
      • Change: from Backend.models.item_model → from models.item_model
      • Change: from Backend.services → from services
    • Add import: import json and import re (for parsing credits from description)

Frontend Work

3.3 Create Utility Functions

    • Copy from SC 12th December version
    • Functions:
      • parseItemMetadata(description) - Extracts metadata from item descriptions
      • getImageUrl(image, apiBaseUrl) - Constructs full image URLs

3.4 Update API Service (Error Handling & Multipart)

    • Enhance error handling:
      • Better parsing of validation errors from backend
      • Handle structured error responses (object with errors array)
      • Network error detection and messaging
      • Validate API_BASE_URL
    • Enhance createItem() function:
      • Properly handle multipart/form-data with images
      • Send JSON string in ‘item’ form field for FastAPI compatibility
      • Better error messages for validation errors
      • Handle both cases: with images (FormData) and without images (JSON)

3.5 Update ProductDetail Component

    • Connect to backend:
      • Import: import { userAPI, itemsAPI } from '@/services/api'
      • Import: import { parseItemMetadata, getImageUrl } from '@/utils/itemParser'
      • Fetch seller information using userAPI.getUser(owner_id)
      • Use parseItemMetadata() to extract metadata from description
      • Use getImageUrl() to construct image URLs
    • Add swap request functionality:
      • Import: import { itemsAPI } from '@/services/api'
      • Update “Swap Now” button to “Request Swap”
      • Add handleSwapClick() function that calls itemsAPI.requestSwap(productData.id)
      • Prevent swapping own items (check isOwner)
      • Check item status (available, pending, swapped)
      • Show appropriate button states based on status and ownership
      • Display user credits from auth context
    • Update UI:
      • Show actual item images from backend
      • Display parsed metadata (condition, size, brand, credits)
      • Better error handling

3.6 Update Profile Component (Backend Integration)

    • Connect to backend:
      • Import: import { itemsAPI, userAPI } from '@/services/api'
      • Import: import { parseItemMetadata, getImageUrl } from '@/utils/itemParser'
      • Fetch user data using userAPI.getUser(authUser.id)
      • Fetch user’s items using itemsAPI.getItems() and filter by owner_id
      • Use parseItemMetadata() and getImageUrl() utilities
    • Remove mock data:
      • Replace all mock data with API calls
      • Add loading and error states
    • Enhanced listings display:
      • Show item status badges
      • Calculate stats from actual data

3.7 Add Documentation

    • Copy from SC 12th December version
    • Documents frontend-backend API integration

Cleanup Work

3.8 Remove Unused Files

    • This folder doesn’t exist in SC 12th December version
    • Can be safely removed
    • Check if this file is still needed
    • The listing functionality appears to be handled elsewhere
    • If not needed, remove it

Testing Checklist


🔄 COORDINATION NOTES

Import Path Changes

All team members need to be aware that import paths are changing from Backend. prefix to relative imports. Make sure to update all imports in files you’re modifying.

Old:

from Backend.services.user_service import get_user_by_id

New:

from services.user_service import get_user_by_id

Dependencies Between Tasks

  • Task 1 depends on Task 2 for credit service (swap approval transfers credits)
  • Task 2 is independent
  • Task 3 is mostly independent but provides utilities used by Task 1

Merge Strategy

  • Each team member should work on a separate branch
  • Merge in order: Task 2 → Task 3 → Task 1
  • Or merge all at once if confident (tasks are mostly non-overlapping)

✅ FINAL VERIFICATION CHECKLIST

After all tasks are complete, verify:


📝 COMMIT MESSAGE TEMPLATES

Task 1

feat: Implement swap request system

- Add swap_service.py for managing swap requests
- Add swap endpoints to item_routes (create, approve, reject, get requests/history)
- Add SwapRequests and SwapHistory frontend components
- Update Profile component with swap tabs
- Add swap API methods to api.js

Task 2

feat: Enhance credit system with transaction tracking

- Update credit_service with transaction types and direct credit updates
- Add automatic 2 credit award on item upload
- Add transaction history tracking
- Update lock/unlock endpoints with ownership checks
- Improve credit service performance

Task 3

feat: Improve core infrastructure and API integration

- Add validation error handler to main.py
- Update all imports to relative paths
- Improve static file mounting
- Add itemParser utility functions
- Enhance API error handling
- Connect ProductDetail and Profile to backend
- Remove unused backend_stuff folder

🚀 GETTING STARTED

  1. Each team member should:
    • Create a new branch: git checkout -b task-{number}-{your-name}
    • Work through their task checklist
    • Test their changes thoroughly
    • Commit and push to their branch
    • Create a pull request to main
  2. After all PRs are reviewed and merged:
    • Test the complete system end-to-end
    • Verify all features work together
    • Push to main branch

Good luck! 🎉