Skip to content

feat: implement AI-powered requirement analysis with hidden internal pricing logic (#76)#80

Closed
devin-ai-integration[bot] wants to merge 3 commits into
mainfrom
devin/1781985064-ai-estimation-final
Closed

feat: implement AI-powered requirement analysis with hidden internal pricing logic (#76)#80
devin-ai-integration[bot] wants to merge 3 commits into
mainfrom
devin/1781985064-ai-estimation-final

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds an AI-powered project estimation system where clients enter a natural-language project description and receive an instant cost/timeline estimate — while all pricing formulas, multipliers, and profit margins remain completely hidden server-side.

Supersedes #77 and #79 (closed due to branch protection rules preventing follow-up pushes).

Architecture (secure two-phase design)

Client (browser)                      Firebase Cloud Function
─────────────────                     ──────────────────────
  description ─── httpsCallable ───►  Phase 1: AI extracts & classifies features
                                        (AI sees category NAMES only, never prices)
                                      Phase 2: Server computes cost deterministically
                                        computeEstimate(classification, pricingConfig)
  ◄── { features, cost, timeline } ── Returns ONLY safe client-facing data

Key security property: the AI prompt never receives pricing values, multipliers, or formulas — it only gets feature category names for classification. All cost/timeline/explanation generation is deterministic server-side code in computeEstimate(). This prevents prompt-injection attacks from leaking internal pricing through free-form AI output.

What's new

functions/src/index.ts — Firebase Cloud Function (analyzeProject):

  • buildClassificationPrompt() sends only feature category names to AI (no prices)
  • validateClassification(data, allowedCategories) performs strict type/enum/category validation
  • computeEstimate() deterministically computes costs, timeline, and explanation
  • getPricingConfig() merges Firestore data with defaults, validates all numeric fields (prices >= 0, multipliers > 0, min <= max, etc.)
  • Input trimmed server-side before validation

src/dashboard/pages/ProjectEstimation.tsx — Client estimation page:

  • Textarea form for free-form project descriptions
  • Animated results: project type, feature breakdown table with complexity badges, cost range, timeline, explanation
  • Expandable estimation history from Firestore

src/dashboard/pages/PricingConfig.tsx — Admin pricing config page:

  • No hardcoded pricing values in the frontend bundle — loads purely from Firestore
  • Access-denied handling for non-admin users (Firestore security rules)
  • Editable grid of feature base prices, complexity multipliers, estimation rules
  • Persists to pricingConfig/default in Firestore

firestore.indexes.json — Composite index for estimations collection (userId ASC + createdAt DESC)

Deployment prerequisites

  1. Firebase Blaze plan (required for Cloud Functions)
  2. Set the Gemini API key: firebase functions:secrets:set GEMINI_API_KEY
  3. Deploy: cd functions && npm install && cd .. && firebase deploy --only functions
  4. Deploy indexes: firebase deploy --only firestore:indexes
  5. Restrict pricingConfig collection to admin-only access in Firestore security rules

Closes #76

Link to Devin session: https://app.devin.ai/sessions/c46ef0652e464fe8b81fbb3cc5147eb3
Requested by: @hrx01-dev

Summary by CodeRabbit

Release Notes

  • New Features

    • AI-powered project estimation: submit project descriptions to receive cost estimates, timelines, and feature breakdowns
    • Pricing configuration management: customize feature pricing and complexity multipliers
  • Chores

    • Added Firebase backend configuration and functions infrastructure

hrx01-dev and others added 3 commits June 20, 2026 19:25
…ic (#76)

- Add Firebase Cloud Function (analyzeProject) that reads pricing config
  from Firestore and calls Gemini API server-side, returning only safe
  client-facing data (features, complexity, cost range, timeline, explanation)
- Add ProjectEstimation dashboard page for clients to submit project
  descriptions and receive instant AI-generated cost estimates
- Add PricingConfig admin page to manage feature prices, complexity
  multipliers, and estimation rules in Firestore
- Add estimation history with expandable records
- Store all pricing logic, prompts, and formulas exclusively server-side;
  API responses never leak internal calculation data
- Add routes (/dashboard/estimation, /dashboard/pricing-config) and
  sidebar navigation entries
- Update firebase.json with functions configuration

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…rministic pricing

- AI prompt now only performs feature extraction/classification with
  category names (no prices, multipliers, or formulas ever sent to AI)
- Cost calculation, timeline estimation, and explanation generation all
  happen deterministically server-side in computeEstimate()
- getPricingConfig() now merges Firestore data with defaults and
  validates numeric bounds to prevent partial/corrupt config
- validateClassification() performs thorough type/enum validation of
  AI output before any downstream processing
- No free-form AI text is returned to the client; explanation is built
  server-side from classification metadata

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…store index

- getPricingConfig: validate all numeric fields, feature prices, and multipliers
- validateClassification: reject categories not in allowed pricing set
- Trim description server-side before validation
- PricingConfig.tsx: remove hardcoded DEFAULT_CONFIG with pricing values;
  load purely from Firestore with access-denied handling
- Add firestore.indexes.json with composite index for estimations query
  (userId ASC + createdAt DESC)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

Adds an end-to-end AI project cost estimation feature. A new Firebase Cloud Function calls the Gemini API to classify project descriptions, applies server-side pricing configuration loaded from Firestore, and persists results. The frontend gains an estimation submission page with history, an admin pricing configuration page, shared TypeScript types, and a service layer. Infrastructure files (firebase.json, firestore index, functions package/tsconfig) are added to support the new functions workspace.

Changes

AI Project Estimation Feature

Layer / File(s) Summary
Shared estimation data contracts
src/dashboard/types.ts
Adds FeatureAnalysis, EstimationResult, and EstimationRecord interfaces shared by the service layer and pages.
Cloud Functions project setup
functions/.gitignore, functions/package.json, functions/tsconfig.json, firebase.json, firestore.indexes.json, eslint.config.js
Wires the new functions workspace: npm scripts, TypeScript config, Firebase hosting/functions/Firestore config, a composite Firestore index on estimations(userId ASC, createdAt DESC), and ESLint ignore entry for functions.
analyzeProject Cloud Function
functions/src/index.ts
Implements the callable function: Admin/Firestore init, pricing data structures with Firestore-backed config, Gemini prompt construction and JSON validation, deterministic cost/timeline computation with risk buffering, Firestore persistence of results, and HttpsError mapping.
Frontend estimation service
src/dashboard/services/estimationService.ts
Adds analyzeProject (calls the Firebase callable, maps response to EstimationResult) and fetchEstimationHistory (queries estimations filtered by userId, ordered by createdAt descending).
PricingConfig admin page
src/dashboard/pages/PricingConfig.tsx
New page that loads pricingConfig/default from Firestore, supports inline editing of feature base prices, complexity multipliers, and estimation rules, and saves via setDoc with loading/access-denied/success/error states.
ProjectEstimation page
src/dashboard/pages/ProjectEstimation.tsx
New page with description form, EstimationResults display (complexity badge, feature table, cost/timeline/explanation cards), collapsible HistoryItem renderer, and history loading gated by currentUser.
Route and nav wiring
src/app/App.tsx, src/dashboard/components/DashboardLayout.tsx
Registers /dashboard/estimation and /dashboard/pricing-config as protected routes and adds corresponding nav items ("AI Estimate", "Pricing Config") with icons to the dashboard sidebar.

Sequence Diagram(s)

sequenceDiagram
  participant User as User (Browser)
  participant ProjectEstimation as ProjectEstimation Page
  participant estimationService as estimationService
  participant analyzeProject as analyzeProject (Cloud Function)
  participant Gemini as Gemini API
  participant Firestore as Firestore

  User->>ProjectEstimation: submit project description
  ProjectEstimation->>estimationService: analyzeProject(description)
  estimationService->>analyzeProject: httpsCallable("analyzeProject", { description })
  analyzeProject->>Firestore: getDoc(pricingConfig/default)
  Firestore-->>analyzeProject: pricing config
  analyzeProject->>Gemini: generateContent(classificationPrompt)
  Gemini-->>analyzeProject: JSON feature classification
  analyzeProject->>analyzeProject: validateClassification() + computeEstimate()
  analyzeProject->>Firestore: addDoc(estimations, result)
  analyzeProject-->>estimationService: EstimationResult payload
  estimationService-->>ProjectEstimation: mapped EstimationResult
  ProjectEstimation-->>User: render cost/timeline/feature breakdown
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • hrx01-dev/Servio#41: Modifies src/app/App.tsx routing structure, which this PR also extends with two new dashboard routes.
  • hrx01-dev/Servio#51: Introduces AuthProvider/useAuth and updates App.tsx routing — both directly consumed by the new estimation pages and protected route wiring in this PR.
  • hrx01-dev/Servio#68: Established the dashboard layout and NAV_ITEMS structure in DashboardLayout.tsx and App.tsx that this PR extends with two new nav entries and routes.

Suggested reviewers

  • hrx01-dev

Poem

🐇 Hop hop, the rabbit types away,
Gemini classifies features today!
Pricing hides safe on the server side,
While cost and timeline charts with pride.
The dashboard gleams with new config art —
A bunny-built AI estimation heart! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main feature: implementing an AI-powered requirement analysis system with hidden internal pricing logic, which matches the core changes throughout the PR.
Linked Issues check ✅ Passed The implementation fully addresses all objectives from issue #76: AI-powered feature analysis via Cloud Function, hidden backend pricing via deterministic server-side computation, client-facing output with non-technical breakdown, admin-controlled pricing configuration, security enforcement through server-side AI prompts and validation, and proper input/output formatting.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #76 objectives: backend Cloud Function implementation, frontend estimation/pricing pages, Firestore configuration, and supporting infrastructure (ESLint, TypeScript, Firebase config) are all necessary for the feature.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch devin/1781985064-ai-estimation-final

Comment @coderabbitai help to get the list of available commands and usage tips.

@hrx01-dev hrx01-dev self-requested a review June 20, 2026 19:52
@github-actions

Copy link
Copy Markdown

Visit the preview URL for this PR (updated for commit 07c8f32):

https://servio-0--pr80-devin-1781985064-ai-qw3dqurv.web.app

(expires Sat, 27 Jun 2026 19:52:37 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 15915abb5951eb298a844eda460b24f444d93a69

@hrx01-dev hrx01-dev left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do the changes suggested by @coderabbitai also don't do cloud functions from firebase that requires blaze plan use some free alternative or leave that thing otherwise

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

Superseded — restructured to remove Firebase Cloud Functions dependency per review feedback.

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.

Implement AI-Powered Requirement Analysis with Hidden Internal Pricing Logic

1 participant