# Enterprise CRM Remediation and Expansion Prompt

You are the principal Laravel architect, enterprise CRM product owner, database
engineer, security reviewer, QA lead, and bilingual UX director responsible for
turning the existing repository into a production-grade CRM for a large company.

## Non-negotiable starting point

Inspect the existing repository before changing it. Preserve working behavior and
user data. The current product is an early prototype, not a completed CRM. Do not
claim otherwise. The current implementation has one meaningful CRUD module
(Leads). Companies, Contacts, Opportunities, Activities, and Tickets are generic
read-only tables served by one `ModuleController`; they have no domain models,
Form Requests, policies, create/edit/detail flows, lifecycle rules, or meaningful
tests. Reports expose only four counts. The mobile menu button and global search
input do not work. Several translations are missing. Authorization is inconsistent
outside Leads. There is no audit trail, notification center, import/export,
automation engine, quotation system, product catalog, pipeline board, SLA engine,
file management, or complete administration console.

Replace prototypes and generic module dispatch with explicit, maintainable domain
implementations. Never create placeholder pages, fake buttons, `href="#"` links,
hard-coded dashboard numbers, or tests that merely assert HTTP 200. Every visible
action must work end-to-end and be authorized server-side.

## Required stack

- Laravel 13.x, PHP 8.3+, MySQL 8.4 production compatibility.
- Blade, Bootstrap 5.3.8, organized CSS/SCSS, vanilla ES modules, Vite.
- PHPUnit 12.
- No React, Vue, Angular, Svelte, Livewire, Inertia, Alpine, Tailwind, jQuery,
  Filament, Nova, admin templates, copied CRM themes, or proprietary assets.
- Specialized small libraries require written justification.

## Phase 0: audit and safe remediation

1. Inventory every route, menu item, button, model, migration, controller, view,
   JavaScript behavior, permission, and test.
2. Create a traceability matrix mapping each visible action to its route,
   authorization rule, validation, transaction, audit event, and tests.
3. Add a data-preserving migration strategy from SQLite development to MySQL.
4. Refactor one-line/minified PHP and Blade into PSR-12, reviewable code.
5. Replace `ModuleController` with explicit resource controllers, models, Form
   Requests, policies, services/actions, factories, seeders, and feature tests.
6. Replace random-loop reference generation with a transaction-safe sequence or
   locked counter that cannot collide under concurrent requests.
7. Ensure related IDs such as `owner_id` and `company_id` are validated within the
   authenticated user's permitted branch/scope, not merely with `exists`.
8. Remove local weak credentials from deployment guidance and add forced first
   login password change for development-created accounts.

## Enterprise platform foundation

Implement multi-branch organization, departments, sales/support teams, territories,
hierarchical managers, job roles, users, invitations, activation/deactivation,
password reset, optional email verification, optional MFA, session management,
login history, and user preferences.

Implement RBAC plus record scope (`own`, `team`, `branch`, `territory`, `all`). Use
Laravel policies for every model and explicit permissions for view, create, update,
delete, restore, permanently delete, assign, import, export, approve, and report.
Prevent cross-branch IDOR everywhere. Cache permissions safely and invalidate the
cache on role changes. Provide an editable permission matrix and tests for every
scope boundary.

Build a real responsive shell: accessible off-canvas mobile navigation, keyboard
navigation, breadcrumbs, command palette/global search, notifications, quick-create,
user menu, saved table views, density settings, column selection, filters, bulk
actions, empty/error/loading states, and WCAG 2.2 AA focus/contrast behavior.

Arabic and English must be complete from the first implementation: RTL/LTR layout,
logical CSS properties, mirrored direction indicators, Arabic validation messages,
localized dates/numbers/currencies, Arabic search normalization, and translated
emails/notifications. Add automated locale coverage and visual browser checks.

## CRM and customer 360

Implement Leads with deduplication, source/campaign attribution, scoring rules,
qualification, assignment queues, round-robin routing, follow-up SLA, disqualification
reasons, merge, bulk update, import/export, and transactional conversion to Company,
Contact, and Opportunity without duplicates.

Implement Companies and Contacts with complete CRUD, multiple addresses/phones/
emails, parent-child organizations, contact roles, preferences/consent, ownership,
territory, tags, custom fields, duplicates/merge, related opportunities, quotations,
tickets, invoices references, activities, notes, files, and a chronological customer
360 timeline.

Provide unified Activities for tasks, calls, meetings, emails, reminders, recurrence,
outcomes, attendees, assignments, priorities, calendar/list views, overdue handling,
and entity linking. Notifications and queued reminders must be idempotent.

## Sales execution

Implement configurable pipelines and ordered stages, probability, stage requirements,
lost reasons, aging, stale-deal warnings, drag-and-drop stage transitions with an
authorized transactional endpoint, immutable stage history, forecasts, weighted
pipeline, products/services, price books, taxes, discounts, multiple currencies,
quotations, versioning, approval thresholds, PDF output, expiry, acceptance/rejection,
and conversion to won business.

Add enterprise features not normally present in basic CRMs:

- Buying committee and relationship-map tracking.
- MEDDICC/BANT qualification templates configurable per pipeline.
- Deal health scoring with explainable factors, not opaque AI claims.
- Mutual action plans shared internally and optionally with customers.
- Revenue leakage alerts for inactive high-value opportunities.
- Forecast scenarios: committed, best case, pipeline, and manager override.
- Territory capacity and account coverage gap reports.
- Approval chains for discounts, non-standard terms, and credit exposure.
- Competitor tracking and win/loss intelligence.

## Customer service and success

Implement tickets with numbered references, channels, requester/company, category,
priority, status, assignment queues, internal/public replies, attachments, watchers,
collision-safe agent presence, business hours, holidays, SLA policies, pause rules,
first-response/resolution clocks, escalations, breach events, canned responses,
knowledge base, CSAT, and full history.

Add customer-success capabilities: onboarding plans, health score, product adoption
signals, renewal dates, risks, success objectives, quarterly reviews, churn reasons,
expansion opportunities, and playbooks triggered by health changes.

## Marketing, operations, and intelligence

Implement sources, campaigns, membership, costs, responses, attribution, ROI, UTM
capture, consent, suppression lists, and lead-source quality reporting. Do not build
bulk email sending without unsubscribe and compliance controls.

Implement targets and commissions with versioned plans, effective dates, tiers,
accelerators, splits, adjustments, approvals, disputes, payout periods, immutable
calculation snapshots, and reconciliation reports.

Implement a safe CSV/XLSX import workflow: template download, upload validation,
column mapping, dry-run preview, duplicate policy, queued chunks, row-level errors,
progress, retry, rollback strategy, and downloadable error file. Exports must be
permission-aware, queued for large datasets, auditable, and protected from formula
injection.

Implement dashboards and reports using real scoped data: funnel conversion, stage
velocity, pipeline coverage, forecast accuracy, activity effectiveness, lead source
ROI, sales cycle, win/loss, rep/team performance, SLA compliance, ticket backlog,
customer health, renewals, and commissions. Support date/branch/team/owner filters,
saved reports, scheduled delivery, drill-down, and export. Test calculations with
known fixtures and edge cases.

## Automation and extensibility

Create a versioned automation engine with trigger, conditions, delayed actions,
execution logs, retry, idempotency keys, recursion limits, dry run, enable/disable,
and permissions. Initial triggers: record created/updated, stage changed, inactivity,
date reached, SLA risk, score threshold, and ticket event. Initial actions: assign,
create activity, notify, update allowed fields, add tag, webhook, and queued email.

Add custom fields with typed validation and indexing strategy, configurable statuses,
tags, saved views, webhooks with signed payloads and delivery logs, API tokens with
abilities and expiry, documented REST endpoints, rate limiting, idempotency for
writes, and API audit logs.

## Security, audit, and data governance

Implement immutable audit entries for authentication, CRUD, assignment, stage
changes, conversion, exports, imports, permission changes, approvals, and settings.
Capture actor, timestamp, branch, IP, user agent, subject, event, and redacted diffs.
Never record passwords, tokens, private file contents, or sensitive secrets.

Private files require randomized storage paths, MIME/content validation, size limits,
malware-scanning integration point, policy-controlled download, expiring URLs where
appropriate, audit logging, and protection from path traversal.

Add retention policies, anonymization workflow, legal hold markers, consent history,
data export/deletion request workflow, backups documentation, recovery verification,
security headers, CSP plan, CSRF, login throttling, secure cookies, session rotation,
mass-assignment protection, allow-listed sorting/filtering, output escaping, and
dependency vulnerability review.

## Performance and reliability

Design for millions of activities and hundreds of thousands of customers. Add
appropriate composite indexes after measuring query plans, eager loading, cursor
pagination where suitable, cache strategy with invalidation, aggregate snapshots,
queued heavy work, idempotent jobs, retry/backoff, failed-job handling, monitoring,
health checks, structured logs, slow-query observation, and scheduler overlap locks.
Avoid N+1 queries and unbounded exports.

## Testing requirements

Use factories and deterministic fixtures. Add unit, feature, integration, queue,
notification, authorization, localization, import/export, calculation, concurrency,
and regression tests. Tests must verify business outcomes and forbidden behavior,
not merely status 200. Include cross-branch IDOR tests for every resource, role/scope
matrix tests, invalid transition tests, duplicate conversion tests, quotation math,
SLA clock rules, commission snapshots, audit redaction, and file authorization.

Run browser checks at desktop, tablet, and mobile widths in English and Arabic.
Verify every menu item and visible action. Check keyboard behavior, focus, validation,
console errors, Laravel logs, empty states, large data tables, and destructive-action
confirmations. No phase is complete while regression tests fail.

## Delivery sequence and gates

Deliver vertical slices, never a collection of empty pages:

1. Platform security and bilingual design system.
2. Customer 360: Leads, Companies, Contacts, Activities.
3. Pipelines, Opportunities, Products, Quotations, approvals.
4. Tickets, SLA, knowledge base, customer success.
5. Campaigns, targets, commissions, imports/exports.
6. Automation, custom fields, API/webhooks, audit, settings.
7. Reports, performance hardening, browser QA, deployment documentation.

For each slice: migrate safely, seed realistic Egyptian/Middle Eastern demo data,
run the complete test suite, inspect logs, verify policies, test Arabic/English and
mobile layouts, document packages and architectural decisions, and fix regressions
before continuing.

## Definition of done

Do not mark a module READY unless all navigation, CRUD/detail flows, validation,
authorization, branch/scope isolation, relationships, history, audit, responsive UI,
Arabic/English behavior, factories, seed data, and automated tests work. Provide a
final traceability matrix, route/action inventory, permission matrix, ERD, package
justifications, installation/deployment/queue/scheduler/backup guides, performance
evidence, browser results, test results, known limitations, and an honest production
readiness verdict.

Begin with an evidence-backed repository audit and remediation plan. Then implement
the highest-risk foundation issues before adding new modules. Never label read-only
generic tables or HTTP-200 tests as completed business functionality.
