# Proactive Suggestion Catalog

> **Version:** 3.0.0
> **Usage:** Loaded by step-01-analyse after scope definition to suggest complementary modules/sections.
> **Protocol:** Match feature type against patterns, present via AskUserQuestion (multiSelect: true).
> **Purpose:** Guide users toward complete feature design by suggesting companion modules and standard sections.

---

## 1. Module Patterns

Suggests companion modules based on primary module type:

| Module Type | Keywords | Suggested Modules | Rationale |
|-------------|----------|-------------------|-----------|
| **Orders/Commandes** | order, commande, purchase, sales order | Invoices, Shipping, Returns, OrderLines, Customers | Orders are complete business objects; need billing, logistics, and related tables |
| **Clients/Customers** | client, customer, contact, account, party | Contacts, Addresses, Contracts, Documents, CRM | Customers have multiple contact types, billing addresses, legal relationships |
| **Products/Articles** | product, article, item, catalog, sku | Categories, Inventory, Pricing, Suppliers, Images | Products need organization, stock tracking, and multiple pricing strategies |
| **Employees/HR** | employee, staff, personnel, team, workforce | Leaves, TimeTracking, Evaluations, Documents, Departments | Employees have time off needs, performance management, and asset allocation |
| **Tickets/Support** | ticket, support, incident, issue, case | SLA, Escalation, KnowledgeBase, Categories, Notifications | Support systems need SLA tracking, knowledge base, and routing logic |
| **Projects** | project, task, milestone, workplan, roadmap | Tasks, Milestones, Resources, Budgets, Timeline | Projects decompose into work items, need resource allocation, and progress tracking |
| **Invoices/Billing** | invoice, billing, payment, receipt, statement | Payments, CreditNotes, Dunning, Taxes, Subscriptions | Invoicing is incomplete without payment tracking, refunds, and tax handling |
| **Inventory/Stock** | inventory, stock, warehouse, goods, warehouse | StockMovements, Locations, Transfers, Alerts, AuditLog | Stock control needs movement tracking, multi-location support, and alerts |
| **Documents** | document, file, attachment, media, archive | Categories, Versions, Sharing, Templates, Workflow | Document management requires metadata, versioning, and access control |
| **Contracts** | contract, agreement, legal, terms, service level | Parties, Obligations, Milestones, Renewal, Templates | Contracts involve multiple parties, obligations tracking, and lifecycle management |
| **Permissions/Security** | permission, role, access, authority, rbac | UserRoles, Groups, Policies, Audit, Delegation | Permission systems need fine-grained control, group policies, and audit trails |
| **Notifications** | notification, alert, email, message, broadcast | Templates, Channels, Scheduling, Preferences | Notification systems need template management, multi-channel support, scheduling |
| **Reporting** | report, dashboard, analytics, BI, metrics | Dashboards, Exports, Scheduling, AlertRules | Reporting needs visualization, scheduled distribution, and data export |

---

## 2. Section Patterns (cross-module)

Suggests standard sections based on detected conditions:

| Condition | Suggested Section | Reason | Implementation |
|-----------|-------------------|--------|-----------------|
| **Volume > 100 entries mentioned** | BulkImport | Large datasets need import capability | Add section with template format (CSV), validation rules, progress tracking |
| **Export mentioned or data analysis** | Export (PDF/Excel) | Common need for business data | Add section with export formats, filtering, custom reports |
| **Multiple user roles (≥3)** | Dashboard | Role-specific views improve UX | Add section with role-based dashboards, KPI cards, drill-downs |
| **Time-sensitive data** | Notifications | Alert users of important changes | Add section with alert rules, channels (email, in-app), scheduling |
| **Approval workflow mentioned** | Validation/Approval | Structured approval process | Add section with approval states, reviewer assignment, audit trail |
| **Historical data important** | AuditLog | Track changes for compliance | Add section with change tracking, versioning, retention policy |
| **Multi-language content** | Translation Management | Content i18n beyond UI labels | Add section with content i18n, translation workflow, versioning |
| **Scheduled processing** | Background Jobs | Deferred/periodic processing | Add section with job scheduling, retry logic, error handling |
| **Data archival needed** | Archive/Cleanup | Long-term data management | Add section with archival policy, retention rules, restore capability |
| **Report generation** | Reporting Engine | Automated business reporting | Add section with template library, scheduling, distribution |
| **External integrations** | Integration Layer | System-to-system communication | Add section with API specifications, webhook handling, sync strategy |
| **Regulatory compliance** | Compliance & Audit | Legal/industry requirements | Add section with audit logging, data retention, retention periods |

---

## 3. Integration Patterns

Suggests system integrations based on requirements:

| Condition | Suggested Integration | Reason | Technical Approach |
|-----------|----------------------|--------|-------------------|
| **Email mentioned** | Workflow: SendEmail | Transactional email automation | Add section with email templates, trigger rules, delivery confirmation |
| **External system referenced** | API Integration | Structured external data flow | Add section with API specs, auth strategy, sync frequency, error handling |
| **Real-time updates needed** | SignalR Integration | Live data push to frontend | Add section with connection management, broadcast strategy, client handling |
| **Scheduled processing** | Hangfire Background Jobs | Deferred/periodic processing | Add section with job scheduling, retry policy, monitoring |
| **AI/ML classification** | AICompletion Service | Intelligent data processing | Add section with model specs, training data, API integration |
| **Document generation** | Templating Engine | Dynamic document creation | Add section with template library, variable mapping, output formats |
| **Payment processing** | Payment Gateway | Financial transaction handling | Add section with provider integration, security, reconciliation |
| **Geographical features** | Maps/Location Service | Spatial data handling | Add section with provider selection, geocoding, distance calculation |
| **Data synchronization** | Event Bus/Messaging | Async data consistency | Add section with message types, subscription strategy, retry logic |
| **File storage** | Cloud Storage Integration | Large file handling | Add section with provider selection, access control, cleanup policy |

---

## 4. Usage Protocol

### 4.1 Trigger Point

After step-01-analyse completes scope definition (scope.mustHave + scope.shouldHave populated):

```
Step-01: Analyse → Define Scope → Load Suggestion Catalog → Present Suggestions
```

### 4.2 Suggestion Algorithm

```
Input: feature.json.scope.* (module name, keywords, must-haves, should-haves)

1. Read scope.mustHave + scope.shouldHave (user-defined features)
2. Extract primary keywords (module type) from scope.description
3. Match against Module Patterns table → Suggested Modules
4. Analyze scope.mustHave + scope.shouldHave for conditions → Suggested Sections
5. Detect mentions of integrations → Suggested Integrations
6. Filter out already-present modules/sections
7. Rank by relevance (keyword match > condition confidence)
8. Present top 3-4 suggestions to user
9. Store results in feature.json.suggestions[]
```

### 4.3 Implementation Code

```typescript
// Pseudo-code for suggestion logic

function suggestComplementaryModules(feature: Feature): Suggestion[] {
  const suggestions: Suggestion[] = [];

  // 1. Extract primary keywords
  const keywords = extractKeywords(feature.scope.description);
  const primaryType = matchModuleType(keywords);

  // 2. Load suggestion catalog
  const catalog = loadCatalog();

  // 3. Suggest companion modules
  if (catalog.modulePatterns[primaryType]) {
    const suggestedModules = catalog.modulePatterns[primaryType].suggestedModules;

    suggestedModules.forEach(module => {
      if (!featureIncludesModule(feature, module)) {
        suggestions.push({
          type: "module",
          name: module,
          rationale: catalog.modulePatterns[primaryType].rationale,
          priority: "high",
          acceptance: `If accepted, adds ${module} as companion feature`
        });
      }
    });
  }

  // 4. Suggest sections based on conditions
  catalog.sectionPatterns.forEach(pattern => {
    if (evaluateCondition(feature, pattern.condition)) {
      if (!featureIncludesSection(feature, pattern.suggestedSection)) {
        suggestions.push({
          type: "section",
          name: pattern.suggestedSection,
          rationale: pattern.reason,
          priority: "medium",
          acceptance: `If accepted, adds ${pattern.suggestedSection} section to spec`
        });
      }
    }
  });

  // 5. Suggest integrations based on mentions
  catalog.integrationPatterns.forEach(pattern => {
    if (feature.scope.description.includes(pattern.keyword)) {
      if (!featureIncludesIntegration(feature, pattern.suggestedIntegration)) {
        suggestions.push({
          type: "integration",
          name: pattern.suggestedIntegration,
          rationale: pattern.reason,
          priority: "medium",
          acceptance: `If accepted, adds ${pattern.suggestedIntegration} to architecture`
        });
      }
    }
  });

  // 6. Rank and filter top suggestions
  const ranked = suggestions
    .sort((a, b) => priorityScore(a) - priorityScore(b))
    .slice(0, 4);

  return ranked;
}

// Evaluate condition: Volume > 100
function evaluateCondition(feature: Feature, condition: string): boolean {
  if (condition === "Volume > 100 entries") {
    const mentions = feature.scope.description.match(/(bulk|import|high.*volume|large.*dataset)/gi);
    return mentions && mentions.length > 0;
  }
  // ... other conditions
}
```

### 4.4 User Presentation

Present suggestions to user via AskUserQuestion (multiSelect: true):

```
✓ Analysis complete. I've identified some complementary modules & sections.

Would you like to add any of these to your feature?

Companion Modules:
  □ Customers (ships with Orders) → Need to manage customer relationships
  □ Shipping (logistics) → Need to track delivery
  □ Invoices (billing) → Need financial records
  □ Returns (warranty) → Need reverse logistics

Standard Sections:
  □ BulkImport → You mentioned "1000+ orders per month"
  □ Notifications → For order status alerts
  □ Dashboard → For manager oversight
  □ Audit Log → For order history tracking

Select all that apply: [ ] [ ] [ ] [ ]

[Add Selected] [Skip] [Customize]
```

### 4.5 User Selection Processing

When user selects suggestions:

1. **Add Selected Modules:** Update scope.mustHave with new modules
2. **Add Selected Sections:** Update specification.sections (in step-02)
3. **Add Selected Integrations:** Update specification.integrations
4. **Store Decisions:** Log in feature.json.suggestions[]
5. **Continue:** Proceed to step-02-specify with expanded scope

```json
{
  "suggestions": [
    {
      "id": "SUGG-001",
      "type": "module",
      "name": "Customers",
      "source": "Module Pattern: Orders → Customers",
      "accepted": true,
      "acceptedAt": "2025-02-01T09:30:00Z",
      "acceptedBy": "user_email@company.com"
    },
    {
      "id": "SUGG-002",
      "type": "section",
      "name": "BulkImport",
      "source": "Section Pattern: Volume > 100",
      "accepted": true,
      "acceptedAt": "2025-02-01T09:30:00Z"
    },
    {
      "id": "SUGG-003",
      "type": "integration",
      "name": "Email Notifications",
      "source": "Integration Pattern: Email mentioned",
      "accepted": false,
      "rejectionReason": "Out of scope for MVP"
    }
  ]
}
```

---

## 5. Customization & Feedback Loop

### 5.1 Customize Suggestions

Allow user to modify or customize suggestions:

```
Option: [Customize]

Edit suggestion "Customers":
  Name: Customers
  Type: Module
  Rationale: [user can edit]
  Include in scope: [Yes/No]

[Apply] [Cancel]
```

### 5.2 Feedback Loop

Track suggestion effectiveness:

```json
{
  "suggestionFeedback": {
    "catalogVersion": "1.0.0",
    "suggestionSessionId": "sess-12345",
    "presentedCount": 4,
    "acceptedCount": 2,
    "acceptanceRate": 0.5,
    "userFeedback": "Perfect - saved us from missing Customer module!"
  }
}
```

---

## 6. Catalog Maintenance

### 6.1 Update Triggers

Update suggestion catalog when:

1. **New patterns discovered** - Team identifies common module combinations
2. **Industry changes** - New regulations, technologies, best practices
3. **User feedback** - Customers request new suggestions
4. **Version upgrades** - New SmartStack capabilities

### 6.2 Catalog Format

Suggestion catalog stored as structured data:

```yaml
# templates/patterns/suggestion-catalog.yaml

version: "1.0.0"
updated: "2025-02-01"

modulePatterns:
  Orders/Commandes:
    keywords: ["order", "commande", "purchase", "sales order"]
    suggestedModules: ["Invoices", "Shipping", "Returns", "OrderLines", "Customers"]
    rationale: "Orders are complete business objects..."

  Customers:
    keywords: ["client", "customer", "contact", "account"]
    suggestedModules: ["Contacts", "Addresses", "Contracts", "Documents"]
    rationale: "Customers have multiple contact types..."

sectionPatterns:
  - condition: "Volume > 100 entries mentioned"
    suggestedSection: "BulkImport"
    reason: "Large datasets need import capability"
    implementation: "Template format (CSV), validation rules, progress tracking"

  - condition: "Export mentioned or data analysis"
    suggestedSection: "Export"
    reason: "Common need for business data"
    implementation: "Export formats (PDF, Excel), filtering, custom reports"

integrationPatterns:
  - condition: "Email mentioned"
    suggestedIntegration: "Workflow: SendEmail"
    reason: "Transactional email automation"
    approach: "Email templates, trigger rules, delivery confirmation"

  - condition: "External system referenced"
    suggestedIntegration: "API Integration"
    reason: "Structured external data flow"
    approach: "API specs, auth strategy, sync frequency, error handling"
```

---

## 7. Limitations & Edge Cases

### 7.1 When Suggestions Don't Apply

Skip suggestions if:

- **Micro mode:** Skip all suggestions (keep MVP minimal)
- **Refactoring mode:** Skip module suggestions (only affect feature sections)
- **User explicitly declines:** Respect user's scope boundary
- **Budget/timeline constraints:** User indicated fixed scope

```
Suggested modules: Customers, Shipping, Invoices, Returns

But you indicated:
  - Timeline: 2 weeks (MVP only)
  - Budget: 1 developer

Suggestion: Start with Orders + Customers (minimal), defer others.

[OK] [Adjust scope] [Ignore suggestions]
```

### 7.2 Conflicting Suggestions

Handle cases where suggestions conflict:

```
Suggestion: BulkImport (volume > 100)
Suggestion: Manual creation only (for quality control)

Conflict: Bulk operations vs. controlled creation.

Recommendation: Add BulkImport with validation workflow.

[Accept both] [Choose one] [Skip both]
```

### 7.3 Chained Dependencies

Track cascading dependencies:

```
User accepted: Customers
Auto-suggest: Addresses (depends on Customers)
Auto-suggest: Contracts (depends on Customers + Addresses)

Cascade depth limit: 2 levels (prevent scope explosion)

Auto-added:
  ✓ Customers (user selected)
  ✓ Addresses (dependency of Customers)
  ⚠ Contracts (optional, user confirm?)

[Accept all] [Customize] [Clear cascade]
```

---

## 8. Examples

### 8.1 Example: Order Management

**Input:**
- Module: "Orders"
- Description: "Manage customer purchase orders, 5000+ orders/month"
- Scope: [Scope definition with "bulk", "export", "approval"]

**Suggestions Generated:**
1. ✓ **Module: Customers** - Orders need customer relationship
2. ✓ **Module: Shipping** - Orders need fulfillment tracking
3. ✓ **Section: BulkImport** - 5000+ orders/month detected
4. ✓ **Section: Export** - Explicit mention in scope
5. ✓ **Section: Dashboard** - 3+ roles (User, Manager, Admin)
6. ✓ **Section: Audit Log** - Order modifications tracked
7. ✓ **Integration: Email Notifications** - Order status alerts
8. ✗ **Module: Invoices** - Deferred (nice-to-have)

**Presented to User (top 4):**
1. Customers - High relevance (module pattern match)
2. BulkImport - High relevance (volume > 100)
3. Dashboard - Medium relevance (multi-role)
4. Email Notifications - Medium relevance (status updates mentioned)

---

### 8.2 Example: Customer Management

**Input:**
- Module: "Customers"
- Description: "Manage customer master data with contacts and addresses"

**Suggestions Generated:**
1. ✓ **Module: Contacts** - Customer subcomponent
2. ✓ **Module: Addresses** - Multiple addresses per customer
3. ✓ **Module: Contracts** - Customer agreements
4. ✓ **Section: Merge** - Duplicate customer handling
5. ✓ **Section: Import** - Master data cleanup
6. ✓ **Integration: API Integration** - External CRM sync

**Presented (top 3):**
1. Contacts - High relevance (decomposition)
2. Addresses - High relevance (decomposition)
3. Merge - Medium relevance (data quality)

---

### 8.3 Example: HR/Employees

**Input:**
- Module: "Employees"
- Description: "Manage employee records and leave requests"

**Suggestions Generated:**
1. ✓ **Module: Leaves** - Leave management system
2. ✓ **Module: TimeTracking** - Time & attendance
3. ✓ **Module: Evaluations** - Performance management
4. ✓ **Section: Calendar** - Leave calendar view
5. ✓ **Section: Reports** - HR analytics and reports
6. ✓ **Integration: Background Jobs** - Payroll processing

**Presented (top 4):**
1. Leaves - High relevance (mentioned in description)
2. TimeTracking - High relevance (related feature)
3. Calendar - Medium relevance (leave visualization)
4. Reports - Medium relevance (HR analytics)

---

---

## 10. Entity Classification Patterns

> **Usage:** Loaded by step-01-cadrage (section 4d-bis) to accelerate entity scoring.
> **Full reference:** `references/entity-architecture-decision.md` (scoring grid, decision tree, section patterns)
> These patterns provide quick pre-classification. Full scoring is still required to confirm.

### 10.1 Toujours Module Dedie (score typique >= 11)

| Entite | Domaines typiques | Pourquoi module dedie |
|--------|-------------------|-----------------------|
| Clients/Customers | CRM, Ventes, Facturation | Hub relationnel central, multi-acteur, lifecycle complet |
| Employes/Employees | RH, Temps, Paie | Acteur central, donnees sensibles, multi-workflows |
| Projets/Projects | Gestion, Temps, Facturation | Lifecycle complexe, multi-ressources, reporting |
| Commandes/Orders | Ventes, Logistique | Workflow d'approbation, etats multiples, sous-entites |
| Factures/Invoices | Finance, Ventes | Obligations legales, workflow complexe |
| Contrats/Contracts | Juridique, RH, Ventes | Lifecycle avec echeances, obligations, renouvellement |
| Produits/Products | Commerce, Inventaire | Catalogue avec variantes, tarification, stock |

**Section pattern for module dedie:**
- Section `list` (TOUJOURS) : grille + bouton create (navigue vers page `/create`) + clic vers detail
- Page detail avec onglets : Infos + onglets relationnels
- Sections additionnelles UNIQUEMENT si : dashboard, approve, import, rapport

### 10.2 Souvent Sous-entite du Parent (score typique 4-6)

| Entite | Module parent typique | Pourquoi sous-entite |
|--------|----------------------|-----------------------|
| Adresses | Clients, Employes | Composant du parent, pas d'autonomie fonctionnelle |
| Notes/Commentaires | Tout module | Sous-objet universel, lie au contexte parent |
| Pieces jointes/Documents | Tout module | Stockage lie au parent, pas de lifecycle propre |
| Lignes de commande | Commandes | Composant structurel, pas de sens seul |
| Tags/Labels | Tout module | Categorisation simple, configurable |
| Contacts (d'un client) | Clients | Personnes liees a l'entite parente |

**Presentation dans le parent:** Onglet dans la page detail du module parent

### 10.3 Toujours Config List (score typique 0-3)

| Entite | Pourquoi config list |
|--------|---------------------|
| Pays, Villes | Reference geographique stable, rarement modifiee |
| Devises | Reference systeme, standard ISO |
| Statuts (types enumeres) | Enum ou lookup, admin-only, < 20 valeurs |
| Unites de mesure | Reference technique stable |
| Codes postaux | Reference externe, pas de CRUD utilisateur |
| Types/Categories simples | Flat list sans hierarchie, configurable par admin |
| Codes d'imputation | Reference comptable, admin-managed, stable |

> **Override rule:** Peut etre promu si le client exprime un besoin de hierarchie (> 2 niveaux), de workflow, ou de permissions specifiques.

### 10.4 Decision Rapide par Domaine

> **Lors de l'approfondissement, si le domaine de l'application est identifie, utiliser ce tableau pour pre-classifier les entites referenciees.**

| Domaine de l'app | Entites typiquement CORE (module) | Entites typiquement SUPPORT (sous-entite/config) |
|-------------------|-----------------------------------|--------------------------------------------------|
| **Gestion du temps** | Employes, Projets, Activites, Absences | Codes d'imputation, Types d'absence, Departements |
| **CRM / Ventes** | Clients, Contacts, Opportunites, Devis | Secteurs, Sources, Etapes de vente |
| **E-commerce** | Produits, Commandes, Clients, Factures | Categories, Tailles, Couleurs, Devises |
| **RH** | Employes, Contrats, Conges, Evaluations | Postes, Departements, Types de contrat |
| **Gestion de projets** | Projets, Taches, Ressources, Jalons | Statuts, Priorites, Types de tache |
| **Finance** | Factures, Paiements, Budgets, Ecritures | Comptes, Journaux, Periodes |
| **Logistique** | Entrepots, Mouvements, Expeditions | Transporteurs, Unites, Zones |

---

## 9. Versioning & Updates

**Catalog Version:** 2.0.0
**Last Updated:** 2026-02-11
**Next Review:** 2026-05-11
**Maintained By:** SmartStack Team

Changes will be tracked in `templates/patterns/suggestion-catalog-changelog.md`.
