GCP Cloud Application for KaamyabPakistan Ecosystem
A Shariah-compliant investment and franchise management platform that unites community capital with entrepreneurial talent through the Musharakah (partnership) model — enabling Pakistanis to build businesses debt-free.
| Platform | Vehicle Type | Focus Areas | Revenue Streams |
|---|---|---|---|
| KaamyabPakistan.org | Social Impact Musharakah | Innovation hubs, training centers | Subscription fees, consulting |
| YouInvent.Tech | Innovation Musharakah | Patent development, prototyping | IP licensing, membership |
| HomeFranchise.Biz | Franchise Musharakah | Micro-franchise units | Product sales, franchise profit |
| NoCodeAI.Cloud | Technology Musharakah | AI platform development | SaaS subscriptions PKR 500–5,000/mo |
| Layer | Technology |
|---|---|
| Cloud | Google Cloud Platform (GCP) |
| Backend | Python 3.12 + FastAPI |
| Frontend | Next.js 14 (React) |
| Database | Firestore + BigQuery |
| Authentication | Firebase Authentication |
| AI/ML | Vertex AI + Claude API |
| Payments | JazzCash / Easypaisa + Stripe |
| Hosting | Cloud Run + Firebase Hosting |
musharakah-platform/
├── services/
│ ├── musharakah-service/ # Pool management, partner matching, profit distribution
│ ├── franchise-service/ # Franchise lifecycle, territory, operations
│ ├── contract-service/ # Shariah-compliant contract generation & management
│ ├── financial-service/ # Ledger, payments, zakat calculation
│ ├── ai-service/ # Risk scoring, matching, analytics
│ ├── auth-service/ # Firebase Auth integration, RBAC
│ └── notification-service/ # Email, SMS, push notifications
├── shared/
│ ├── models/ # Shared data models
│ ├── utils/ # Common utilities
│ └── config/ # Environment configuration
└── gateway/
└── api-gateway/ # Request routing, rate limiting, auth middleware
| Service | Purpose | Monthly Cost |
|---|---|---|
| Cloud Run | Backend microservices hosting (auto-scaling) | $50–200 |
| Firestore | Primary database (real-time, NoSQL) | $25–100 |
| BigQuery | Analytics, reporting, financial aggregation | $20–80 |
| Cloud Storage | Contract PDFs, documents, media files | $5–20 |
| Firebase Auth | User authentication, phone OTP | $0–25 |
| Firebase Hosting | Next.js frontend static hosting + CDN | $0–25 |
| Vertex AI | ML models for risk scoring and matching | $30–100 |
| Cloud Scheduler | Cron jobs: profit distribution, reports | $1–5 |
| Cloud Tasks | Async task processing (contracts, notifications) | $1–5 |
| Secret Manager | API keys, payment gateway credentials | $1–5 |
| Cloud Logging | Application logs, audit trail | $10–30 |
| Pub/Sub | Event-driven messaging between services | $5–15 |
| Cloud Armor | DDoS protection, WAF | $10–20 |
| Estimated Total | $230–730/month | |
Start at $230/mo using GCP free tier credits and scale-to-zero Cloud Run. Costs increase proportionally with user base. At 10,000 active users, expect mid-range costs. BigQuery on-demand pricing keeps analytics costs low during early phases.
Core user identity across the platform.
uid — Firebase Auth UID (primary key)full_name — Full legal namecnic — National ID (encrypted)phone — Mobile number (verified)email — Email addressroles[] — Assigned platform roleskyc_status — pending | verified | rejectedpostal_code — Territory identifierplatform_source — Originating platformcreated_at / updated_atInvestment pool where partners contribute capital.
pool_id — Auto-generated unique IDpool_name — Descriptive nameplatform — KP | YI | HF | NCtarget_amount — Capital goal (PKR)raised_amount — Currently raisedstatus — fundraising | active | distributing | closedmusharakah_type — permanent | diminishingprofit_sharing_ratio — JSON partner ratiosshariah_approved — Boolean + advisor refpartners[] — Array of partner referencesIndividual franchise operation linked to a Musharakah pool.
franchise_id — Unique identifierpool_id — Linked Musharakah pooloperator_uid — Assigned operatorbusiness_type — Franchise categoryterritory — Postal code assignmentsetup_cost — Total establishment coststatus — setup | operating | paused | closedmonthly_revenue — Latest reported revenueperformance_score — AI-calculated scoreShariah-compliant legal agreement between parties.
contract_id — Unique identifiercontract_type — musharakah | franchise | partnershipparties[] — UIDs of all contract partiesterms — JSON structured termsshariah_clauses[] — Required clausesstatus — draft | review | signed | active | expiredpdf_url — Cloud Storage pathsignatures[] — Digital signaturesDouble-entry accounting record.
entry_id — Unique identifierpool_id — Associated poolentry_type — investment | revenue | expense | distributiondebit_account / credit_accountamount — Transaction amount (PKR)description — Human-readable notereference_id — Linked transactioncreated_by — User who recordedRecord of profit distribution to partners.
distribution_id — Unique identifierpool_id — Source poolperiod — Month/quarter coveredtotal_revenue / total_expensesnet_profit — Distributable profitallocations[] — Per-partner breakdownzakat_deduction — 2.5% if applicablestatus — calculated | approved | disbursedCross-platform project linking pools to real-world initiatives.
project_id — Unique identifierplatform — Originating platformproject_name — Descriptive nameproject_type — hub | training | franchise | saaspool_ids[] — Associated investment poolsmilestones[] — Progress trackingimpact_metrics — Jobs created, revenue generatedstatus — planning | funded | active | completedCore business logic for Islamic partnership management.
Manages franchise operations across the ecosystem.
Generates and manages Shariah-compliant legal documents.
Intelligence layer powered by Vertex AI and Claude.
function distribute_profit(pool_id, period):
pool = get_pool(pool_id)
franchise = get_franchise(pool.franchise_id)
// Calculate net profit for the period
total_revenue = sum(franchise.revenue[period])
total_expenses = sum(franchise.expenses[period])
net_profit = total_revenue - total_expenses
if net_profit <= 0:
// Loss shared proportionally by capital ratio
for partner in pool.partners:
partner.loss = net_profit * (partner.capital / pool.total_capital)
return LossRecord(pool_id, period, allocations)
// Deduct management fee (platform share)
platform_fee = net_profit * pool.platform_ratio // e.g., 10%
distributable = net_profit - platform_fee
// Distribute per agreed Musharakah ratio
allocations = []
for partner in pool.partners:
share = distributable * partner.profit_ratio
allocations.append({ partner.uid, share })
// Record in ledger
create_ledger_entries(allocations)
trigger_payouts(allocations)
return ProfitDistribution(pool_id, period, net_profit, allocations)
function generate_buyout_schedule(pool_id, duration_months):
pool = get_pool(pool_id)
operator = get_operator(pool.operator_uid)
total_buyout = pool.total_capital - operator.initial_investment
monthly_unit = total_buyout / duration_months
schedule = []
operator_share = operator.initial_investment / pool.total_capital
for month in range(1, duration_months + 1):
// Operator buys one unit of partner equity
buyout_amount = monthly_unit
operator_share = operator_share + (monthly_unit / pool.total_capital)
// Recalculate profit ratios for next period
new_ratios = recalculate_ratios(pool, operator_share)
schedule.append({
month,
buyout_amount,
operator_ownership: operator_share * 100, // percentage
remaining_buyout: total_buyout - (monthly_unit * month),
profit_ratios: new_ratios
})
// Final month: operator owns 100%
assert schedule[-1].operator_ownership == 100.0
return BuyoutSchedule(pool_id, duration_months, schedule)
RESTful API served via FastAPI on Cloud Run. All endpoints prefixed with /api/v1. Authentication via Firebase JWT tokens.
| Route | Page | Description |
|---|---|---|
/ | Landing | Hero, value proposition, CTA to invest or operate |
/auth/* | Auth Pages | Login, register, OTP verification, KYC upload |
/dashboard | Dashboard | Role-based overview with key metrics |
/pools | Pool Explorer | Browse and filter Musharakah pools |
/pools/[id] | Pool Detail | Partners, financials, documents, timeline |
/pools/create | Pool Creation | Multi-step wizard for new pools |
/franchises | Franchise Directory | All franchise units with map view |
/franchises/[id] | Franchise Detail | Operations, revenue, performance charts |
/contracts | Contract Center | Active and pending contracts |
/investments | My Investments | Portfolio view with returns tracking |
/financials | Financial Hub | Ledger, distributions, payment history |
/admin/* | Admin Panel | User management, system config, reports |
| # | Template | Parties | Use Case |
|---|---|---|---|
| 1 | Musharakah Pool Agreement | All pool partners | Establishing investment partnership |
| 2 | Diminishing Musharakah Schedule | Partners + Operator | Buyout terms over 3–5 years |
| 3 | Franchise Operating Agreement | Pool + Operator | Franchise rights and obligations |
| 4 | Partner Entry Agreement | New partner + Pool | Adding investor mid-pool |
| 5 | Partner Exit Agreement | Exiting partner + Pool | Early partner withdrawal |
| 6 | Profit Distribution Notice | Pool to all partners | Monthly/quarterly profit statement |
| 7 | Platform Service Agreement | Platform + Pool | Managing partner terms |
| 8 | Shariah Compliance Certificate | Shariah Board + Pool | Certification of compliance |
No interest-based returns. All profits derived from actual business activity. No guaranteed fixed returns; investors share in actual profits and losses.
Profits distributed per agreed ratio. Losses shared strictly proportional to capital contribution. Operator losses are limited to effort/labor.
All contracts reviewed by qualified Shariah advisor. Annual compliance audit. Mandatory Shariah board approval for new pool types.
Investment restricted to Halal business activities only. Prohibited sectors: alcohol, gambling, tobacco, conventional finance, pork products.
Disputes resolved through Shariah arbitration first. Escalation path: Mediation → Shariah Arbitration → Civil Court (Pakistan).
Platform calculates zakat obligation on idle capital (2.5% annually). Zakat deducted and distributed to eligible recipients per Shariah guidelines.
1000 Cash & Bank Accounts1100 JazzCash Receivable1200 Easypaisa Receivable1300 Stripe Receivable1400 Partner Capital Receivable1500 Franchise Inventory1600 Equipment & Assets2000 Partner Capital Payable2100 Profit Distribution Payable2200 Zakat Payable2300 Tax Obligations2400 Vendor Payable3000 Franchise Product Sales3100 Service Income3200 SaaS Subscriptions3300 IP Licensing Revenue3400 Consulting Income3500 Training Fees4000 Cost of Goods Sold4100 Operating Expenses4200 Platform Management Fee4300 Technology & Hosting4400 Marketing & Outreach5000 Partner Equity5100 Retained Earnings5200 Operator Buyout EquityPrimary gateway for Pakistan-based transactions.
Secondary gateway for maximum coverage.
International gateway for overseas investors.
Firebase Authentication with phone OTP as primary method. Role-Based Access Control (RBAC) enforced at both API gateway and service levels. Users may hold multiple roles.
| Permission | Community Investor | External Financier | Franchise Operator | Managing Partner | Shariah Advisor | Platform Admin |
|---|---|---|---|---|---|---|
| View pools | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Invest in pools | ✓ | ✓ | — | ✓ | — | ✓ |
| Create pools | — | — | — | ✓ | — | ✓ |
| Operate franchise | — | — | ✓ | — | — | ✓ |
| Submit revenue | — | — | ✓ | ✓ | — | ✓ |
| Approve contracts | — | — | — | ✓ | ✓ | ✓ |
| Shariah review | — | — | — | — | ✓ | ✓ |
| Trigger distributions | — | — | — | ✓ | — | ✓ |
| View all financials | — | — | — | ✓ | ✓ | ✓ |
| Manage users | — | — | — | — | — | ✓ |
| System configuration | — | — | — | — | — | ✓ |
Infrastructure-as-Code via Terraform. All services deployed to GCP us-central1 region with automatic scaling and zero-downtime deployments.
cloud-run — Service definitions, scaling rules, env varsfirestore — Database indexes, security rulescloud-storage — Buckets for contracts, media, backupsbigquery — Dataset, tables, scheduled queriescloud-scheduler — Cron jobs for distributions, reportsiam — Service accounts, roles, permissionsnetworking — VPC, Cloud Armor, load balancermonitoring — Alerts, uptime checks, dashboards| Environment | Project ID | Purpose |
|---|---|---|
| Development | kp-musharakah-dev | Feature development, testing |
| Staging | kp-musharakah-staging | Integration testing, UAT |
| Production | kp-musharakah-prod | Live platform |
| Job | Schedule | Action |
|---|---|---|
| Profit Calc | 1st of month | Calculate pool distributions |
| Zakat Calc | Annually (Ramadan) | Calculate zakat obligations |
| Reports | Weekly (Monday) | Generate performance reports |
| Backup | Daily (2 AM) | Firestore export to GCS |
| Cleanup | Weekly (Sunday) | Remove expired tokens, temp files |
24-week implementation plan divided into 6 phases. Each phase delivers working, deployable increments following agile methodology.
Total duration: 24 weeks (6 months). Each phase delivers a working increment that can be demoed and tested.