# Ascend ERP / CRM Product Guide

## 1. Executive Summary

Ascend ERP is a unified business management platform built from the IDURAR MERN ERP/CRM foundation and expanded into a multi-module operating system for growing companies. It brings CRM, sales, finance, inventory, vendor operations, POS, marketing, AI agents, automation, forms, reporting, task management, and access control into one connected workspace.

The purpose of the app is to remove the split between sales activity, customer records, invoices, inventory, marketing follow-up, and management oversight. Instead of each department working in separate tools, Ascend ERP stores shared records in one tenant-scoped database and connects modules through workflows, automation events, permissions, audit logs, and notifications.

The platform is designed for:

- SMEs and mid-market businesses that need CRM, invoicing, inventory, and operations in one system.
- Retail or branch-based businesses that need POS and stock visibility.
- Service businesses that need quotes, invoices, appointments, contracts, and document workflows.
- Marketing and growth teams that need campaign creation, social scheduling, AI content, lead capture, and lead follow-up.
- Admin teams that need users, roles, permissions, auditability, provider keys, and controlled integrations.

## 2. What The App Does

At a high level, Ascend ERP helps a company:

1. Capture leads from forms, landing pages, public calculators, and manual entry.
2. Manage contacts, companies, customers, leads, and deal pipelines.
3. Create quotes, offers, proforma invoices, invoices, payments, and sales orders.
4. Track revenue, expenses, budgets, taxes, currencies, ledgers, and payment reconciliation.
5. Manage products, stock, purchase orders, vendors, suppliers, and branch-level availability.
6. Run a retail POS flow with cashier sessions, checkout, receipts, barcode support, and daily/monthly reports.
7. Build campaigns, generate content, schedule social posts, and track marketing performance.
8. Create custom AI agents for content, strategy, lead generation, competitor research, social operations, budget planning, expense intelligence, and brand governance.
9. Automate cross-module workflows from events such as "deal won", scheduled rules, campaign responses, and failed payments.
10. Manage tasks, reminders, appointments, bookings, documents, contracts, and operational work.
11. Control users, roles, permissions, branch access, onboarding, password setup, active sessions, and audit-sensitive actions.
12. Expose module data through REST-first APIs for integrations and future external clients.

## 3. Product Principles

The product is built around these principles:

- **One shared operating record:** contacts, leads, sales, invoices, payments, stock, vendors, campaigns, tasks, and automation events are linked instead of duplicated across departments.
- **Tenant isolation first:** every business workspace is tenant-scoped so records do not cross between organizations.
- **API-layer authorization:** permissions are enforced by backend middleware, not only hidden in the UI.
- **Workflow-first UX:** high-volume modules use guided workbenches and operator screens; generic record management remains available for admin/debug use.
- **Automation as a shared engine:** modules publish events into one automation system instead of each module inventing separate automation logic.
- **AI as a controlled operator assistant:** AI can draft, analyze, recommend, and prepare actions, but sensitive publishing, finance, export, and outbound actions require approval.
- **NGN default, multi-currency capable:** Nigerian Naira is the default currency while the finance layer remains multi-currency.

## 4. High-Level Architecture

```mermaid
flowchart LR
  User["Operator / Admin / Cashier / Marketer"] --> Frontend["React + Vite + Ant Design Frontend"]
  Frontend --> API["Express REST API"]
  API --> Auth["Auth Token Validation"]
  Auth --> Tenant["Tenant Resolver"]
  Tenant --> RBAC["RBAC + Field Policy"]
  RBAC --> Modules["CRM / Sales / Finance / Inventory / POS / Marketing / AI / Automations"]
  Modules --> Mongo["MongoDB + Mongoose Models"]
  Modules --> Events["Automation Event Bus"]
  Events --> Jobs["Mongo-backed Job Queue"]
  Jobs --> Runners["Automation Runner / Agent Runner / Social Publisher"]
  Runners --> Providers["Resend / Meta / OpenAI / Kimi / Hermes / Fal.ai"]
  Modules --> Audit["Audit Logs"]
  Modules --> Notify["Notifications"]
```

### Frontend

The frontend is a React/Vite application using Ant Design, Redux, route-level lazy loading, guided workflow pages, and a generic entity manager fallback.

Primary frontend areas include:

- Dashboard
- CRM
- Sales
- Marketing
- Finance
- Catalog / Inventory
- POS
- Vendors
- Operations
- Tasks
- AI Studio
- Automations
- Platform / Settings

### Backend

The backend is an Express API with Mongoose models and route conventions under `/api/<entity>`. It includes:

- Auth routes for login, logout, forget password, and reset password.
- Tenant and RBAC middleware.
- Generic CRUD routes for registered app entities.
- Workflow endpoints for conversions, payments, POS, automation, agents, social publishing, notifications, forms, reports, and user management.
- Public endpoints for hosted forms and the solar load calculator.

### Database

MongoDB is the primary database. Most business models use shared platform fields such as:

- `tenant`
- `removed`
- `createdBy`
- `assignedTo`
- `created`
- `updated`

This supports tenant isolation, soft delete, assignment, ownership, and auditability.

## 5. Core Modules

## 5.1 Dashboard

The dashboard gives management and operators a fast view of business health.

It shows:

- Invoice, quote, payment, customer, and revenue summaries.
- Paid, unpaid, overdue, draft, and proforma indicators.
- Recent invoices, quotes, payments, customers, expenses, and operational records.
- NGN-formatted financial cards.
- Quick actions into the strongest workflow screens instead of raw records.
- Date-range filters such as recent periods and business-wide summaries.

Typical users:

- Business owner
- Finance officer
- Sales manager
- Operations manager

## 5.2 CRM Workspace

The CRM module manages the relationship layer of the business.

Core records:

- Customers
- People / contacts
- Companies
- Leads
- Deals
- Offers / proforma records
- Pipeline stages
- Activities
- Communication logs

Key capabilities:

- Create and manage customer and contact records.
- Capture leads from forms, public pages, calculators, campaigns, and manual entry.
- Track lead source, status, owner, score, and activity.
- Move deals through a pipeline.
- Log calls, notes, emails, WhatsApp, SMS, meetings, and tasks.
- Attach activities and calculator submissions to a contact timeline.
- Convert qualified opportunities into quotes, orders, invoices, tasks, and campaigns.

Important flows:

1. A prospect submits a form or load calculator.
2. The system creates or reuses a CRM contact.
3. The system creates or reuses a lead.
4. The activity timeline stores the submission, source, UTM data, and details.
5. Sales qualifies the lead and creates a deal or offer.
6. The deal can become a quote, order, invoice, task, and automation trigger.

## 5.3 Sales Management

The sales module handles the commercial path from proposal to payment.

Core records:

- Offers
- Quotes
- Invoices
- Payments
- Sales orders
- Sales targets
- Approval requests

Key capabilities:

- Create quotes and commercial offers.
- Convert offers/proforma records into invoices.
- Generate invoices from deals or sales workflows.
- Record payments against invoices.
- Reconcile payments.
- Track order, quote, invoice, and payment statuses.
- Support approval workflows for discounts or threshold-sensitive transactions.
- Link sales activity to CRM contacts, finance records, inventory, vendors, and automation events.

Important flows:

### Quote To Invoice

1. Sales creates a quote or offer.
2. Customer approves the pricing.
3. User converts the quote/offer.
4. Finance receives an invoice.
5. Payment is recorded and reconciled.
6. Activity and audit logs preserve the history.

### Deal Won

1. Sales moves a deal to `Won`.
2. The system publishes a `crm.deal.won` event.
3. Automation can create a sales order.
4. Finance invoice can be generated.
5. Vendor/procurement can be notified if fulfillment is needed.
6. Marketing can trigger thank-you or onboarding communication.

## 5.4 Marketing Automation

Marketing helps the company create, launch, schedule, monitor, and optimize campaigns.

Core records:

- Campaigns
- Audience segments
- Landing forms
- Public forms
- Form definitions
- Campaign events
- Social posts
- Content assets

Key capabilities:

- Build campaigns across email, SMS, WhatsApp, and social channels.
- Segment audiences from CRM data.
- Capture leads through public forms and hosted URLs.
- Launch campaigns with content, schedule, audience, and channel review.
- Generate AI content directly inside campaign flows.
- Schedule social posts for supported business channels.
- Track campaign events and feed engagement back into lead scoring.
- Create follow-up automations from campaign outcomes.

Important flows:

### Public Form Lead Capture

1. Admin creates a public form using the form builder.
2. Form is published with a public URL.
3. Website visitor submits the form.
4. Backend validates required fields.
5. CRM contact and lead are created or reused.
6. Form submission stores the raw payload.
7. Optional auto-reply is sent through Resend.
8. Automation event is published for follow-up.

### Website Load Calculator Lead Capture

1. Visitor opens `/load-calculator/:tenantSlug`.
2. Visitor enters appliances, quantity, wattage, and usage hours.
3. Calculator estimates total watts, daily energy, inverter size, battery size, and solar array size.
4. Visitor submits name, email, phone, project type, location, and notes.
5. UTM parameters, referrer, and landing page are included.
6. CRM contact and lead are created or reused.
7. Activity timeline stores the calculation breakdown and attribution.
8. Sales can follow up with a proposal.

## 5.5 Finance Management

Finance handles accounting, receivables, payables, expenses, tax, budgets, and financial documents.

Core records:

- Accounts
- Ledger entries
- Invoices
- Payments
- Expenses
- Expense categories
- Bills
- Budgets
- Currencies
- Payment modes
- Taxes
- PDF settings
- Finance documents

Key capabilities:

- Create and manage invoices.
- Record payments against invoices.
- Reconcile payments.
- Track paid, unpaid, partial, overdue, and draft statuses.
- Log expenses and categorize spend.
- Track accounts payable and vendor bills.
- Maintain budget plans and variance.
- Configure taxes per region.
- Manage default currency and multi-currency records.
- Configure invoice, quote, receipt, barcode, and report print settings.
- Upload and manage finance documents.

Default currency:

- `NGN`
- Symbol: `₦`

Important flows:

### Invoice Payment Reconciliation

1. Finance opens an invoice.
2. User records a payment amount, method, reference, and date.
3. Backend validates the amount against outstanding balance.
4. Payment record is created.
5. Invoice credit and payment status are updated.
6. Finance can reconcile the payment.
7. Audit and reporting reflect the change.

## 5.6 Catalog, Inventory, And Procurement

This module manages the product catalog, branch stock, orders, purchase orders, suppliers, and vendor-linked procurement.

Core records:

- Products
- Product categories
- Inventory stock
- Stock movements
- Orders
- Purchase orders
- Suppliers
- Vendors

Key capabilities:

- Create products and categories.
- Track SKU, barcode values, stock quantity, reorder level, and pricing.
- Track branch-level stock through `InventoryStock`.
- Record inbound and outbound stock movement.
- Manage order and purchase status transitions.
- Link purchase orders to vendors/suppliers.
- Surface low-stock and replenishment signals.
- Generate barcode outputs from SKU/product code.

Important flows:

### Procurement To Stock

1. Manager identifies low-stock product.
2. Purchase order is created.
3. Purchase order moves through approval and processing.
4. Received stock increases branch availability.
5. Stock movement logs inbound quantity.
6. POS and inventory availability update.

## 5.7 Point Of Sale

POS is a retail cashier workflow for fast sales recording.

Core records:

- POS sessions
- POS sales
- POS receipts
- Inventory stock
- Stock movements

Key capabilities:

- Open and close cashier sessions.
- Select branch.
- Search or scan products.
- Add items to cart.
- Validate stock at branch level.
- Complete checkout.
- Generate receipt payload.
- Optionally create invoice/payment records for finance visibility.
- Decrement stock automatically.
- Reprint receipts.
- Generate barcode output.
- View daily and monthly POS reports.
- Export POS sales.

Important flow:

### Cashier Checkout

1. Cashier opens an active POS session for a branch.
2. Cashier searches or scans a product.
3. System shows availability and blocks out-of-stock checkout.
4. Cashier edits quantity and payment method.
5. Checkout creates a POS sale and receipt.
6. Stock movement is logged for each sold item.
7. Branch stock decreases.
8. Session totals update.
9. Manager views reports by day, month, branch, payment mode, and product.

## 5.8 Vendor Management

Vendor management coordinates suppliers, service vendors, contracts, purchase orders, and performance.

Core records:

- Vendors
- Vendor contracts
- Purchase orders
- Vendor scorecards
- Bills
- Payments

Key capabilities:

- Vendor onboarding and status management.
- Contract storage and terms tracking.
- Purchase order creation and approval.
- Payment terms and vendor-linked accounts payable.
- Scorecards for quality, delivery, and cost.
- Integration with inventory procurement and finance AP.

## 5.9 Operations Workspace

Operations covers internal resources, scheduling, branches, contracts, and documents.

Core records:

- Branches
- Company workspaces
- Calendar bookings
- Appointments
- Documents
- Contracts

Key capabilities:

- Manage branches and operating locations.
- Configure company workspaces and default currency.
- Book meetings and appointments.
- Store internal documents.
- Manage contracts and operational agreements.
- Link tasks and appointments back to CRM or sales records.

## 5.10 Task Management

Task management gives teams a separate operational module for follow-up work.

Core records:

- Tasks
- Reminders
- Appointments
- Linked entities

Key capabilities:

- Create tasks manually or from automations.
- Assign tasks to users.
- Link tasks to contacts, deals, invoices, campaigns, or vendor records.
- Track status, due dates, priority, and ownership.
- View task board and calendar-style routes.
- Support reminders and appointment handoffs.

Important flows:

- Create follow-up task after new lead capture.
- Create task after campaign click or response.
- Create task from automation when a deal, invoice, or social event needs human attention.
- Use reminders to keep activities from becoming stale.

## 5.11 AI Studio And Agent Platform

AI Studio is not only a content generator. It is a platform for creating, testing, publishing, and monitoring custom AI agents.

Core records:

- Agent definitions
- Agent versions
- Agent runs
- Agent run steps
- Agent approvals
- Agent tools
- Knowledge sources
- Knowledge documents
- Knowledge chunks
- Brand profiles
- Social connections/posts
- Agent budgets
- Content assets

Key capabilities:

- Create agents from templates or from scratch.
- Use an in-house assistant to draft agent setup.
- Configure purpose, knowledge, tools, guardrails, schedule, test, and publish stages.
- Use provider-neutral LLM routing for OpenAI, Kimi, Hermes, and future providers.
- Use Hermes as orchestration provider where configured.
- Add knowledge from ERP records, files, and approved websites.
- Store brand voice, banned phrases, tone, visual identity, and guidelines.
- Generate text assets such as newsletters, emails, blogs, captions, flyer copy, scripts, and prompts.
- Generate brand-aligned images/flyers through Fal.ai provider integration.
- Schedule social posts from AI-created assets.
- Monitor agent runs, costs, approvals, and failures.
- Manage agent budgets in NGN.

Specialist agent templates include:

- Marketing Strategy Agent
- Social Media Manager
- Lead Generation Agent
- Competitor Analysis Agent
- Web Research Agent
- Budget Planning Agent
- Expense Intelligence Agent
- Brand Guardian
- Content Production Agent

Approval model:

- Low-risk analysis and drafts can run automatically.
- Sensitive CRM updates, task creation, social scheduling, and finance recommendations can require approval.
- Outbound messages, live publishing, budget allocation, expense changes, exports, and destructive actions require stricter control.
- AI agents must not exceed user or service-account permissions.

Important flow:

### Build And Publish An Agent

1. User opens AI Studio.
2. User chooses a template or starts from scratch.
3. User defines the agent purpose.
4. User attaches knowledge sources.
5. User selects allowed tools.
6. User sets guardrails and approval requirements.
7. User schedules or tests the agent.
8. Test mode runs with external writes disabled.
9. User reviews steps, cost, and approval preview.
10. User explicitly publishes the agent.
11. Agent run history stores outputs, tool calls, and status.

## 5.12 Automation Console

Automation is the shared workflow engine across modules.

Core records:

- Automation rules
- Automation events
- Automation runs
- Jobs

Key capabilities:

- Build event, field-change, and scheduled triggers.
- Add conditions.
- Add ordered action stacks.
- Preview rule behavior against sample events.
- Run due jobs manually.
- View run history.
- Retry failed runs.
- Monitor queued jobs and failed actions.
- View scheduled automation calendar.

Supported first-pass actions include:

- Create record
- Update record
- Send email
- Send WhatsApp
- Generate content
- Create task
- Schedule social post
- Create invoice
- Create purchase order

Important flow:

### Shared Automation Event

1. Module publishes an event.
2. Automation event is stored.
3. Matching rules create due jobs.
4. Runner claims queued jobs.
5. Automation run is created.
6. Actions execute sequentially.
7. Results or errors are stored.
8. Notifications and audit logs are created where appropriate.

## 5.13 Notifications

Notifications help users see what needs attention without checking every module manually.

Core records:

- Notifications
- Notification preferences

Key capabilities:

- In-app notification creation.
- Email delivery through Resend when configured.
- WhatsApp delivery through Meta when configured.
- Unread count.
- Notification drawer.
- Read/read-all actions.
- Preferences per user.

Notification triggers include:

- Agent approval requested.
- Automation approval requested.
- Agent run failed.
- Automation run failed.
- Social post failed or published.
- Scheduled run completed.
- Budget threshold reached.
- Expense anomaly detected.
- Reminder due.
- Provider connection failed.
- Hermes unavailable or fallback activated.
- POS session close summary.
- Low-stock alerts.

## 5.14 Forms And Public Lead Capture

The form builder supports both internal and public forms through one field-definition system.

Core records:

- Form definitions
- Form field definitions
- Form submissions
- Public forms

Supported field types:

- Text
- Textarea
- Number
- Select
- Checkbox
- Date
- Email
- Phone

Key capabilities:

- Build structured forms without raw JSON editing.
- Publish hosted public forms.
- Capture internal submissions.
- Route submissions to CRM records.
- Create CRM leads automatically.
- Store raw payloads for traceability.
- Send optional auto-replies.
- Use public forms on websites or landing pages.

## 5.15 Reports

Reports summarize operational and financial performance.

Minimum reporting areas:

- Invoices and payments
- Customers and leads
- Quotes and offers
- Expenses
- Orders and purchases
- POS daily/monthly sales
- Inventory low stock
- Campaign and social performance
- Agent costs and run health

Reports are designed to respect tenant scope, RBAC, and export controls.

## 5.16 Settings, User Management, And Security

Settings contains the administrative control layer.

Key areas:

- User management
- Access control
- Roles and permissions
- Integration/provider accounts
- API keys
- Currency, payment mode, tax, PDF settings
- Notification preferences
- Print settings
- Public forms/form builder

User management capabilities:

- Create users.
- Assign roles.
- Assign branch access.
- Enable/disable users.
- Reset password.
- Generate setup links.
- Show pending setup status.
- Inspect sessions.
- Revoke one session or all sessions.
- Review effective permissions.

RBAC model:

- Module-level permissions such as `crm.contact.read`.
- Action permissions such as `sales.quote.create`.
- Workflow permissions such as `automations.retry`.
- Field restrictions for sensitive fields.
- Branch/user/team scoping where supported.
- Audit tracking for sensitive changes.

Default role examples:

- Admin
- Sales Rep
- Sales Manager
- Finance Officer
- Vendor Manager
- Marketing Manager
- Cashier

Security features:

- JWT login/session validation.
- Session tracking through logged token records.
- Rate limiting for auth and API routes.
- CORS restrictions in production.
- Security headers.
- Tenant resolver middleware.
- RBAC middleware.
- Audit logs.
- Soft-delete behavior on platform records.

## 6. Main User Flows

## 6.1 Admin Onboards A New User

1. Admin opens Settings.
2. Admin opens User Management.
3. Admin clicks New User.
4. Admin enters name, email, role, branch access, and direct permissions if needed.
5. System creates the user and password record.
6. System generates temporary password and setup link.
7. Admin sends setup link to user.
8. User opens the setup link.
9. User sets password.
10. User lands inside the app.
11. Admin can later inspect or revoke active sessions.

## 6.2 Sales Team Captures And Converts A Lead

1. Lead comes from public form, load calculator, campaign, or manual entry.
2. CRM creates/reuses contact.
3. CRM creates/reuses lead.
4. Sales logs calls, notes, and qualification activity.
5. Sales creates deal or offer.
6. Deal moves through pipeline.
7. Deal is marked won.
8. Automation creates downstream records such as order, invoice, task, campaign, or procurement request.

## 6.3 Finance Records Payment

1. Finance opens invoice.
2. User records payment.
3. Backend validates payment amount.
4. Payment is attached to invoice.
5. Invoice payment status updates.
6. Finance reconciles payment.
7. Dashboard and reports update.

## 6.4 Cashier Completes POS Sale

1. Cashier opens POS.
2. Cashier opens session for branch.
3. Cashier adds product to cart.
4. System validates branch stock.
5. Cashier completes checkout.
6. POS sale and receipt are created.
7. Stock movements are logged.
8. Branch stock decreases.
9. Session totals update.
10. Manager views report.

## 6.5 Marketer Launches Campaign

1. Marketer opens Marketing.
2. Marketer selects goal and channel.
3. Marketer chooses audience segment.
4. Marketer drafts or imports AI content.
5. Marketer previews content by channel.
6. Marketer schedules send/social posts.
7. Campaign launch checklist confirms readiness.
8. Campaign is launched or scheduled.
9. Campaign events update performance and lead scoring.
10. Marketer creates follow-up automation.

## 6.6 Operator Builds An Automation

1. Operator opens Automations.
2. Operator chooses starter template or custom builder.
3. Operator selects trigger.
4. Operator adds conditions.
5. Operator adds actions.
6. Operator runs preview against sample event.
7. Operator activates rule.
8. Event bus publishes matching events.
9. Jobs are queued and processed.
10. Runs, failures, retries, and notifications are visible.

## 6.7 Growth User Builds An AI Agent

1. User opens AI Studio.
2. User chooses template.
3. User configures purpose, knowledge, tools, guardrails, schedule, and budget.
4. User runs test simulation.
5. System displays planned steps, approvals, and estimated cost.
6. User publishes agent explicitly.
7. Agent runs on demand or schedule.
8. Approvals pause sensitive actions.
9. Runs, outputs, tool calls, and costs are monitored.

## 6.8 Website Visitor Uses Load Calculator

1. Visitor opens public calculator link.
2. Visitor enters appliances.
3. Calculator computes energy estimate.
4. Visitor submits contact details.
5. System captures UTM/source/referrer metadata.
6. CRM contact and lead are created or reused.
7. Activity log stores appliance breakdown.
8. Sales follows up with proposal.

## 7. API Overview

The backend is REST-first.

Representative endpoints:

- `POST /api/login`
- `POST /api/logout`
- `POST /api/resetpassword`
- `GET /api/admin-access/users`
- `POST /api/admin-access/users`
- `POST /api/admin-access/users/:id/reset-password`
- `GET /api/admin-access/users/:id/sessions`
- `DELETE /api/admin-access/users/:id/sessions`
- `DELETE /api/admin-access/users/:id/sessions/:sessionId`
- `PATCH /api/deal/:id/stage`
- `POST /api/workflows/deal-won`
- `POST /api/offer/convert/:id`
- `POST /api/invoice/:id/record-payment`
- `PATCH /api/payment/:id/reconcile`
- `POST /api/campaign/launch`
- `POST /api/automation/run-due`
- `GET /api/automation/run-history`
- `GET /api/automation/calendar`
- `POST /api/agent/:id/test`
- `POST /api/agent/:id/run`
- `GET /api/agent/run/history`
- `GET /api/agent/calendar`
- `GET /api/social/calendar`
- `POST /api/social/post/schedule`
- `POST /api/social/post/:id/approve`
- `POST /api/pos/session/open`
- `POST /api/pos/checkout`
- `GET /api/pos/report`
- `GET /api/form-builder/definitions`
- `POST /api/form-builder/definition`
- `POST /api/form-builder/submit/:id`
- `GET /api/reports/overview`
- `GET /api/notification`
- `GET /api/notification/unread-count`

Public endpoints:

- `GET /public/builder-forms/:slug`
- `POST /public/builder-forms/:slug/submit`
- `GET /public/load-calculator/:tenantSlug`
- `POST /public/load-calculator/:tenantSlug/submit`

Generic entity endpoints:

- `POST /api/<entity>/create`
- `GET /api/<entity>/read/:id`
- `PATCH /api/<entity>/update/:id`
- `DELETE /api/<entity>/delete/:id`
- `GET /api/<entity>/list`
- `GET /api/<entity>/search`
- `GET /api/<entity>/filter`
- `GET /api/<entity>/export`

## 8. Data And Relationship Overview

Important relationships:

- Tenant owns users, roles, permissions, records, integrations, automation, forms, and AI data.
- Admin users belong to a tenant and can have roles, direct permissions, branch access, manager, and org unit.
- Contacts can link to companies, vendors, leads, deals, activities, and communication logs.
- Leads link to contacts and can become deals/offers.
- Deals link to quotes, offers, invoices, campaigns, tasks, and automation events.
- Quotes/offers can convert to invoices.
- Invoices link to clients/customers and payments.
- Sales orders can link to inventory and purchase orders.
- Purchase orders link to suppliers/vendors, stock movements, bills, and payments.
- POS sales link to sessions, products, branch stock, receipts, and payments.
- Campaign events link back to contacts and lead scoring.
- Tasks/reminders/appointments can link to any module entity.
- AI agents can use knowledge sources, tools, brand profiles, budgets, approvals, and run histories.
- Automation rules react to events from any module and create jobs/runs/actions.

## 9. Permissions And Access Model

Access control is designed around layered checks:

1. User authenticates with JWT.
2. Backend validates active session.
3. Tenant is resolved.
4. RBAC checks module/action permission.
5. Field restrictions can mask/deny sensitive fields.
6. Controllers apply tenant scope and soft-delete filtering.
7. Sensitive actions are audited.

Common permission namespaces:

- `crm.*`
- `sales.*`
- `finance.*`
- `inventory.*`
- `marketing.*`
- `vendors.*`
- `operations.*`
- `tasks.*`
- `ai.*`
- `automations.*`
- `settings.*`
- `platform.*`

Examples:

- `crm.lead.read`
- `sales.quote.create`
- `finance.invoice.update`
- `inventory.pos.create`
- `marketing.social.approve`
- `ai.agent.publish`
- `automations.retry`
- `settings.admin.update`

## 10. Integrations And Provider Accounts

Provider accounts can be configured by admins in the UI and backed by encrypted integration-account storage.

Supported or planned provider categories:

- Email: Resend
- Social/WhatsApp: Meta
- LLM content: OpenAI, Kimi
- Orchestration: Hermes
- Media generation: Fal.ai
- Future providers: OpenAI-compatible LLMs, accounting, payment gateways, and messaging APIs

Provider behavior:

- Runs in disabled/mock mode when keys are absent.
- Secrets should be stored through provider account UI or deployment environment variables.
- Sensitive provider errors should be recorded without exposing secrets.
- Agent and automation runs should capture provider usage and failure status.

## 11. Operational Controls

Current operational controls include:

- User creation and onboarding setup links.
- Password reset flow.
- Active session viewing and revocation.
- Role and permission assignment.
- Branch access assignment.
- Audit-sensitive action logging.
- Notification preferences.
- Integration account management.
- Production CORS and rate limits.
- Health check endpoint.
- Soft delete and tenant isolation patterns.
- Export endpoints respecting RBAC and tenant scope.

Recommended next controls:

- Force session revocation after role/branch changes.
- Require password change on next login.
- Optional 2FA/OTP.
- Auth-specific audit view.
- Device/IP labeling for sessions.
- Export reason prompts for sensitive reports.
- Retention policies for logs, automation runs, and AI prompts.

## 12. Typical User Roles

### Admin

Manages users, roles, permissions, provider accounts, platform settings, and high-risk workflows.

### Sales Rep

Works leads, contacts, deals, offers, quotes, and follow-up tasks.

### Sales Manager

Reviews team pipeline, approvals, forecast, targets, and deal conversion.

### Finance Officer

Manages invoices, payments, reconciliation, expenses, budgets, taxes, and reports.

### Vendor Manager

Manages vendors, contracts, purchase orders, scorecards, and procurement handoffs.

### Marketing Manager

Builds campaigns, segments audiences, drafts content, schedules social posts, and monitors campaign performance.

### Cashier

Uses POS checkout, opens/closes sessions, records sales, and prints/reprints receipts.

### Operations Manager

Manages branches, appointments, bookings, documents, contracts, and operational tasks.

## 13. Demo Storyline

Use this storyline for client demonstrations:

1. Start on the dashboard and show NGN totals, recent invoices, and quick actions.
2. Open CRM and show customers, leads, people, and companies.
3. Create or inspect a lead from the load calculator.
4. Move into deals and mark a deal as won.
5. Show how automation can create order, invoice, task, and campaign follow-up.
6. Open invoice and record a payment.
7. Open finance dashboard and show reconciliation/status.
8. Open inventory and show products, low stock, purchase orders, and suppliers.
9. Open POS and show session, cart, checkout, receipt, and stock update.
10. Open Marketing and show campaign composer, audience, AI content, and social schedule.
11. Open AI Studio and show agent library, builder, brand center, social scheduler, and budgets.
12. Open Automations and show builder, operations history, and calendar.
13. Open Settings and show user management, setup link, roles, access preview, and sessions.
14. End with reports and export options.

## 14. Deployment And Production Notes

Production readiness depends on environment configuration and operational setup.

Minimum backend variables:

- `NODE_ENV=production`
- `DATABASE`
- `JWT_SECRET`
- `INTEGRATION_ENCRYPTION_KEY`
- `CORS_ALLOWED_ORIGINS`

Recommended backend variables:

- `TRUST_PROXY=true`
- `AUTOMATION_WORKER_ENABLED=true`
- `AGENT_WORKER_ENABLED=true`
- `OPENAI_API_KEY`
- `KIMI_API_KEY`
- `HERMES_API_KEY`
- `RESEND_API`
- `META_ACCESS_TOKEN`
- `FAL_KEY`

Frontend variables:

- `VITE_BACKEND_SERVER=https://api.yourdomain.com/`
- `VITE_DEMO_MODE=false`

Production checklist:

1. Configure MongoDB production database and backups.
2. Configure backend environment variables.
3. Configure frontend backend URL.
4. Disable demo mode.
5. Configure HTTPS and reverse proxy.
6. Set CORS origins to trusted domains only.
7. Configure provider credentials.
8. Run backend tests.
9. Build frontend.
10. Smoke-test login, dashboard, CRM lead capture, invoice/payment, POS checkout, automation, AI provider settings, and user management.

## 15. Glossary

- **Tenant:** A company workspace with isolated users and data.
- **Admin:** A user account in the system, not necessarily full administrator access.
- **RBAC:** Role-based access control.
- **Field policy:** Rules that deny or mask sensitive fields.
- **Automation event:** A business event published by any module.
- **Automation run:** A processed automation rule execution.
- **Job:** A queued async task for automation, agent, social, notification, or ingestion work.
- **Agent:** A configured AI worker with purpose, knowledge, tools, guardrails, and schedule.
- **Approval:** A required human decision before a sensitive action executes.
- **Content asset:** AI-created or reusable marketing material.
- **POS session:** Cashier operating window for checkout.
- **Stock movement:** Inventory quantity change caused by sale, receipt, or adjustment.
- **Form definition:** A reusable field schema for public or internal forms.
- **Load calculator:** Public customer-facing calculator that creates CRM leads.

## 16. Current Product Status

The application has moved beyond the original IDURAR invoice/quote/customer baseline into a unified ERP/CRM operating platform. The strongest production-shaped areas are:

- Dashboard
- CRM and lead capture
- Sales, invoices, and payments
- Finance workbench
- Inventory and POS
- User management and access control
- AI Studio and provider management
- Automation runner and monitoring
- Forms and public lead generation
- Notifications and task workflows

The areas that should continue to mature are:

- Deeper financial accounting reports.
- Full provider sandbox verification.
- More robust AI cost governance.
- Device/IP metadata on sessions.
- More granular branch and record possession scopes.
- Richer PDF/report export templates.
- Full end-to-end browser test coverage.

