PromptHub
Back to Blog
Developer Tools Enterprise Software

Open Mercato: The AI-Native Framework Killing CRM Build vs. Buy

B

Bright Coding

Author

14 min read 92 views
Open Mercato: The AI-Native Framework Killing CRM Build vs. Buy

Open Mercato: The AI-Native Framework Killing CRM Build vs. Buy

Your AI assistant just wrote 500 lines of perfect TypeScript. Where do they go? Six months later, your "smart" codebase is a graveyard of inconsistent patterns, security holes, and architectural decisions that made sense to Claude at 2 AM. You've seen it. You've lived it. And if you're a CTO who finally deployed Cursor across your team only to watch productivity plateau—not explode—you're about to discover why.

The dirty secret of 2025's AI coding revolution? Generating code is trivial. Architecting it isn't. Agents don't know your tenancy model. They can't see your RBAC matrix. They have zero clue where the sales pipeline logic ends and the order management system begins. Every "helpful" suggestion fragments your codebase further until you're spending senior engineer hours on code review that should be automated.

Enter Open Mercato—the open-source AI-Engineering Foundation Framework that flips the script entirely. Built with AI and for AI, it embeds hundreds of architectural and domain decisions directly into the repository itself. Multi-tenancy, role-based access control, event flows, pricing engines, CRM processes, ERP workflows—these aren't afterthoughts. They're conventions that agents can read, understand, and extend without reinventing the wheel.

This isn't another boilerplate. This is a production-grade operating system for business applications where your AI tools finally know where to place code, not just how to write it. Ship faster. Ship safer. Let your team focus on the 20% that actually differentiates your business. Ready to see how? Let's tear it open.


What Is Open Mercato?

Open Mercato is an open-source foundation framework for building enterprise CRM, ERP, and commerce systems—engineered from the ground up for AI-assisted development. Created by the team at Catch The Tornado and maintained by a growing community, it represents a fundamental shift in how we think about AI-native application architecture.

The framework's core premise is disarmingly simple yet revolutionary: AI code assistants generate code, but they don't make architectural decisions. Open Mercato solves this by shipping with the decisions already made. Every module, every entity, every API endpoint follows documented conventions that both humans and agents can reference. The result? Reproducible AI output that actually fits your system.

Open Mercato is trending now because it arrives at a critical inflection point. Thousands of engineering teams adopted Cursor, Copilot, and Claude Code in 2024-2025, only to hit the same wall—generated code that works in isolation but collapses at scale. The framework's "spec-first development" approach, where design documents live alongside code in .ai/specs/, creates a teachable, traceable architecture that entire teams can adopt simultaneously. No more AI assistance siloed to your senior engineers.

Built on Next.js↗ Bright Coding Blog App Router, TypeScript, MikroORM, and Awilix dependency injection, Open Mercato ships with ready-made domain modules for CRM, sales pipelines, order management, catalogs, and more. It's MIT-licensed with no per-seat pricing trap—full code ownership, full extensibility, full transparency. For CTOs who've tasted AI coding tools and hunger for more, this is the missing infrastructure layer.


Key Features That Separate Open Mercato From the Herd

Architecture-Aware AI Harness. This is Open Mercato's secret weapon. The framework doesn't just tolerate AI assistants—it structures itself for them. Agents receive autonomous skills for everything from adding data tables to implementing complete features with unit and integration tests. They know where to place code because the architecture is explicit, not implicit. Design-system-coherent forms, proper layering, consistent patterns across 50-engineer teams—baked in, not hoped for.

Spec-First Development. Before any feature ships, its design lives in .ai/specs/ with dated, versioned markdown↗ Smart Converter files. This means AI output becomes reproducible—the same prompt yields the same architectural decision twice. Humans and agents share a single source of truth. Traceability isn't an afterthought; it's the workflow.

Multi-Tenant by Default. SaaS readiness isn't a plugin. Every entity carries tenant_id + organization_id. Organization trees with hierarchical visibility controls are native. You can spin up customer portals, partner ecosystems, or internal divisions without architectural retrofitting.

Feature-Based RBAC. Combine per-role and per-user feature flags with organization scoping. Gate any page or API dynamically. The security model grows with your complexity instead of cracking under it.

Custom Entities & Dynamic Forms. Declare fields, validators, and UI widgets per module—then manage them live from the admin interface. Your business users evolve the data model without deployment cycles. MikroORM handles migrations per module, no global schema lock-in.

Event-Driven Workflows. Publish domain events and process them via persistent subscribers—local or Redis-backed. Orchestrate custom data lifecycles per tenant or team without hard-coding business logic into your core.

Field-Level Encryption. Tenant-scoped AES-GCM encryption with Vault/KMS integration (or derived-key fallback). PII stays protected while CRUD and APIs work with plaintext. Deterministic hashes enable encrypted lookups without exposure.

Modern Stack, Zero Compromise. Next.js App Router, TypeScript, Zod validation, Awilix DI, MikroORM, bcryptjs—battle-tested tools assembled with architectural discipline, not hype-driven chaos.


Where Open Mercato Destroys the Competition: Real-World Use Cases

🛒 B2B Commerce & CPQ Platforms

Configure-price-quote flows are notorious for domain complexity. Open Mercato's reusable commerce modules—catalog, sales channels, offers, orders—let you launch B2B ordering portals in weeks, not quarters. The pricing engine handles tiered, negotiated, and dynamic pricing without custom rebuilds.

💼 CRM Without the Salesforce Tax

Model customers, opportunities, and bespoke workflows with infinitely flexible data definitions. The deals pipeline, people management, and timeline notes ship functional out-of-the-box. Your 20% customization layer sits cleanly on top of 80% solved domain problems—no per-seat pricing, no API limits, no data hostage situations.

🏭 ERP for Operations That Don't Fit Boxes

Manage orders, production coordination, and service delivery while tailoring modules to your operational reality. The modular entity system with automation hooks means you're not forcing your business into someone else's software—you're extending software to match your business.

🌐 Headless API Platforms

Expose rich, well-typed APIs for mobile and web apps using the same extensible data model. Your frontend teams move independently while the backend maintains consistency. The auto-discovered API structure means documentation stays current without manual effort.

🤝 Self-Service Customer Portals

Spin up configurable forms, guided flows, and granular permissions for customers or partners. Multi-tenant scoping ensures data isolation without architectural gymnastics. Approval workflows with explicit mutation policies keep AI-assisted changes safe.


Step-by-Step Installation & Setup Guide

Open Mercato offers two paths: monorepo for core contributions and full platform demos, or standalone app for building your product without touching framework internals.

Prerequisites

  • Node.js 24 (download)
  • Git
  • PostgreSQL↗ Bright Coding Blog + Redis (easiest via docker↗ Bright Coding Blog.com/products/docker-desktop/">Docker Desktop)

Monorepo Setup (macOS/Linux)

# Install Node.js 24
brew install node@24   # or: nvm install 24 && nvm use 24

# Enable Yarn 4 via corepack
corepack enable && corepack prepare yarn@4.12.0 --activate

# Clone and enter the repository
git clone https://github.com/open-mercato/open-mercato.git
cd open-mercato && git checkout develop

# Start infrastructure services
docker compose up -d                  # PostgreSQL, Redis, Meilisearch

# Configure environment
cp apps/mercato/.env.example apps/mercato/.env
# Edit apps/mercato/.env: set DATABASE_URL, JWT_SECRET, REDIS_URL

# Install, build, seed, and start
yarn dev:greenfield

Access the backend at http://localhost:3000/backend—credentials print in terminal.

Standalone App Setup (macOS/Linux)

# Same Node.js and Yarn preparation as above

# Scaffold your application
npx create-mercato-app my-app
cd my-app

# Start infrastructure
docker compose up -d

# Configure .env with DATABASE_URL, JWT_SECRET, REDIS_URL

# Install, seed, start
yarn setup

Windows PowerShell Setup

# Run as Administrator, or use Git Bash/cmd
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
corepack enable; corepack prepare yarn@4.12.0 --activate

# Remaining steps parallel macOS/Linux with path adjustments
Copy-Item apps\mercato\.env.example apps\mercato\.env
# ... configure and run yarn dev:greenfield or yarn setup

Running Multiple Local Instances

For parallel development environments on shared PostgreSQL:

# Explicit database name with .env update (default: yes)
yarn dev:greenfield --database-name=client_a

# Derive database name from working directory
yarn dev --database-name

# One-off run without touching .env
yarn dev --database-name=review_1720 --no-update-env

Production deployment? Guides cover Docker dev, VPS setup, Dev Containers, and Railway one-click deploy.


REAL Code Examples: Inside Open Mercato's Architecture

Let's examine actual patterns from the Open Mercato repository that demonstrate its AI-native design philosophy.

Module Auto-Discovery Pattern

Every feature lives under src/modules/<module> with auto-discovered frontend/backend pages, APIs, CLI, i18n, and DB entities. This convention eliminates the "where does this go?" problem for AI agents:

// A module's structure is self-describing:
// src/modules/crm/
//   ├── entities/          # MikroORM entities (auto-discovered)
//   ├── pages/             # Next.js pages (auto-routed)
//   ├── api/               # API routes (auto-registered)
//   ├── cli.ts             # Module-specific commands
//   ├── di.ts              # Dependency injection registrations
//   └── i18n/              # Translations (auto-loaded)

The di.ts file is particularly powerful. Modules register and override services/components via Awilix's per-request container:

// src/modules/crm/di.ts - Example pattern
import { createModule } from '@open-mercato/core';
import { DealService } from './services/DealService';
import { DealRepository } from './repositories/DealRepository';

export default createModule(({ container }) => {
  // Register module services with lifecycle management
  container.register({
    dealService: asClass(DealService).scoped(),  // Per-request scope
    dealRepository: asClass(DealRepository).singleton()  // Shared across requests
  });
  
  // Override core services with CRM-specific behavior
  // without modifying platform code
});

Why this matters for AI: An agent adding a new feature knows exactly where to place files, how to register dependencies, and how to scope them—no architectural guessing required.

Multi-Tenant Entity Definition

Entities carry tenancy natively. Here's the pattern MikroORM uses with automatic scoping:

// src/modules/directory/entities/TenantOrganization.ts
import { Entity, PrimaryKey, Property, ManyToOne } from '@mikro-orm/core';
import { Tenant } from './Tenant';

@Entity()
export class TenantOrganization {
  @PrimaryKey()
  id!: string;

  @ManyToOne(() => Tenant)
  tenant!: Tenant;  // Every entity belongs to exactly one tenant

  @Property()
  name!: string;

  @Property({ nullable: true })
  parentOrganizationId?: string;  // Hierarchical organizations

  @Property()
  createdAt: Date = new Date();
}

The ORM middleware automatically injects tenant_id filters into every query. Your agents never accidentally expose cross-tenant data because the framework prevents it structurally, not by convention.

Event Subscriber Workflow

Domain events decouple your modules. Here's how persistent subscribers work:

// src/modules/orders/subscribers/OrderFulfillmentSubscriber.ts
import { EventSubscriber, OnEvent } from '@open-mercato/core';

@EventSubscriber('order.confirmed')
export class OrderFulfillmentSubscriber {
  constructor(
    private readonly inventoryService: InventoryService,
    private readonly notificationService: NotificationService
  ) {}

  @OnEvent()
  async handleOrderConfirmed(event: OrderConfirmedEvent): Promise<void> {
    // Decrement inventory for each line item
    await this.inventoryService.reserveStock(
      event.orderId,
      event.lineItems
    );
    
    // Notify warehouse team via their preferred channel
    await this.notificationService.sendToRole(
      'warehouse_manager',
      {
        type: 'new_fulfillment_task',
        orderId: event.orderId,
        priority: event.customerTier === 'enterprise' ? 'urgent' : 'normal'
      }
    );
  }
}

Events publish to Redis-backed queues in production, local memory in development—zero configuration change between environments. Agents implement new workflows by following the subscriber pattern, not by reinventing message bus architecture.

AI Assistant Integration with Mutation Approval

The AI assistant system demonstrates Open Mercato's safety-first approach to agentic operations:

// Embedded in module pages: <AiChat context="customer-exploration" />
// Agents are scoped by:
// - Module permissions (can this user access CRM features?)
// - Tool allowlists (read-only vs. write operations)
// - Mutation policies (explicit approval for data changes)

// Configuration example from admin UI:
{
  "assistantId": "catalog-merchandiser",
  "allowedTools": ["searchProducts", "updatePricing", "generateDescription"],
  "mutationPolicy": "explicit_approval",  // All writes staged for review
  "maxTokensPerInteraction": 4000,
  "tenantOverride": false  // Cannot escape tenant scope
}

Operators tune prompts, downgrade mutation policies, and disable individual tools per tenant without redeploying. This is operational control that generic AI wrappers simply don't provide.


Advanced Usage & Best Practices

Eject When You Need To. Official modules install via npm and stay isolated, but run --eject to copy any module into your app and own it fully. This is your escape hatch when the 80% solution needs the final 20% of customization.

Leverage Spec-Driven Development. Before implementing, check .ai/specs/ for existing designs. Create dated specs for new features ({YYYY-MM-DD}-{title}.md). Update changelogs after changes. This discipline transforms chaotic AI output into maintainable, reviewable architecture.

Use Database Name Overrides for Parallel Work. The --database-name flag lets multiple developers or review apps share one PostgreSQL server without collision. Combine with --no-update-env for ephemeral environments.

Stress Test Before Production. The bootstrap command yarn mercato init --stresstest generates thousands of synthetic contacts, companies, deals, and timeline interactions. Use --stresstest --lite for high-volume contact testing without heavier extras. Know your performance boundaries before go-live.

Monitor AI Assistant Mutations. The approval card system isn't friction—it's auditability. Configure stricter policies for sensitive modules (pricing, user permissions) and looser ones for safe operations (content generation, search).


Open Mercato vs. The Alternatives: Why This Wins

Dimension Open Mercato Salesforce/HubSpot Strapi/Directus Custom Build
Code Ownership Full (MIT) None Full (varies) Full
Per-Seat Pricing Zero $$$$ Zero Zero
AI-Native Architecture Built-in Bolt-on None You build it
CRM/ERP Modules 80% ready 100% rigid None 0% start
Multi-Tenancy Native Complex add-on Plugin Build from scratch
RBAC Granularity Feature + org + user Role-based Basic Build from scratch
Customization Depth Unlimited Limited/Apex API-only Unlimited
Team AI Onboarding Teachable specs N/A N/A Ad-hoc chaos
Time to Production Weeks Days (limited) Months Months/Years

The verdict: Open Mercato occupies the unique intersection of open-source freedom, enterprise domain depth, and AI-native architecture. You get Salesforce-class business logic without the lock-in, Strapi-class extensibility without starting from zero, and custom-build flexibility without the architectural burden.


FAQ: What Developers Actually Ask

Is Open Mercato production-ready? Yes. The framework powers live deployments with enterprise subscription support available. Growing test coverage, field-level encryption, and documented production deployment guides provide operational confidence.

How does AI assistance differ from Cursor/Copilot alone? Cursor generates code. Open Mercato tells Cursor where to place it, how to structure it, and what patterns to follow. The spec system makes AI output reproducible across your entire team, not just individual developers.

Can I use only the CRM module without the ERP features? Absolutely. The modular architecture means you enable only what you need. Each module is independently installable and ejectable.

What's the learning curve for my existing Next.js team? Minimal if you know Next.js App Router, TypeScript, and dependency injection. The conventions are explicit and documented. Most teams report productivity gains within days, not weeks.

How does multi-tenancy handle data isolation? Every database query is automatically scoped to tenant_id + organization_id at the ORM level. No manual filter application, no accidental exposure. Encryption adds field-level protection for sensitive columns.

Is there commercial support available? Yes. The Open Mercato Enterprise Subscription includes architecture audits, production readiness reviews, security reviews, priority support, and a dedicated customer success manager.

Can I contribute modules back to the community? The Official Modules repository accepts reviewed submissions. Each module installs in one command, stays isolated, and can be ejected when needed.


Conclusion: The Framework AI-Assisted Development Desperately Needed

Open Mercato isn't chasing the AI hype cycle—it's solving the architectural crisis that hype created. When every developer on your team can generate working code in seconds, the bottleneck shifts decisively to architecture, consistency, and domain knowledge. Open Mercato embeds that knowledge into the repository itself, making your AI assistants genuinely useful at scale instead of dangerously productive in isolation.

The "80% done" promise isn't marketing fluff. It's a pragmatic recognition that CRM, ERP, and commerce systems share massive common ground, while your competitive differentiation lives in the final 20%. Stop rebuilding authentication pipelines. Stop debating folder structures. Stop hoping your AI tools understand multi-tenancy.

Start with the foundation that thinks like your best architect and works like your fastest agent.

👉 Clone Open Mercato on GitHub and run yarn dev:greenfield today. Join the Discord community for real-time support. Explore the live demo to see what's possible. The future of AI-native business applications isn't coming—it's already here, and it's open source.

Ship it pro. Ship it fast. They've got you.

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!

Recommended Prompts

View All
All tools