# Analysis Methods — FK Detection, Tenant Modes, Code Patterns, Gap Analysis

> **Loaded by:** step-01-analyze.md (sections 4-7)
> **Purpose:** Detailed methods for analyzing existing code and planning entity-level requirements.

---

## FK Field Detection

For each entity found (or to be created), identify FK relationships:
- Properties ending in "Id" with matching navigation property
- Record: `{ entity, fkProperty, targetEntity, isRequired }`

**Why:** FK fields drive two critical requirements:
1. **Frontend:** Each FK field MUST use `<EntityLookup />` (not `<input>`, not `<select>`)
2. **Backend:** Each target entity's GetAll MUST support `?search=` parameter + return `PaginatedResult<T>`

See `references/smartstack-frontend.md` section 6 for EntityLookup patterns.

---

## Tenant Mode Decision

For each entity found (or to be created), determine the `tenantMode`:

| Mode | Meaning | Examples | EF Filter |
|------|---------|----------|-----------|
| `strict` | Data belongs to one tenant | Employee, Order, Invoice | `TenantId == current` |
| `optional` | Can be shared or tenant-specific | Department, Currency, JobTitle | `TenantId == current OR TenantId == null` |
| `scoped` | Explicit scope rules | Settings, Workflow, EmailTemplate | `TenantId == current AND Scope == current` |
| `none` | Shared across all tenants (not filtered) | Navigation, Permission, User | No TenantId |

**Why:** Tenant mode drives EF query filters, seed data generation, and API access control.

**Reference:** See `references/smartstack-api.md` for TenantId handling patterns and `smartstack-layers.md` for seed data strategies per tenant mode.

---

## Code Pattern Detection

For each entity found (or to be created), identify code generation needs using the following **priority order**:

```
PRIORITY 1 — User choice from scope validation (step-00):
  IF {code_patterns} is set (from step-00 section 5c):
    → Use {code_patterns} for each entity
    → This is the user's explicit choice — always takes precedence

PRIORITY 2 — feature.json (from /business-analyse):
  IF feature.json exists AND entity has codePattern:
    → Use codePattern config from feature.json (strategy, prefix, digits, etc.)
    → Record in analysis: entity has auto-generated code

PRIORITY 3 — Heuristic fallback (delegate mode only):
  IF delegate_mode AND no code pattern from Priority 1 or 2:
    → Apply heuristic default based on entity name:
      Invoice/Order/Receipt/PurchaseOrder → timestamp-daily
      Ticket/Incident/SupportRequest → timestamp-minute
      Contract/Policy/Agreement → year-sequential
      Category/Status/Type (reference data) → uuid-short
      Employee/Customer/Project → sequential
    → Note: heuristic applied — PRD was incomplete

FALLBACK — Manual (safest default):
  IF none of the above apply:
    → strategy: "manual" (Code field in CreateDto, user-provided)
    → No auto-generation, no ICodeGenerator injection
```

**Important:** In interactive mode (no `-d` flag), heuristics are never applied silently. The user is always asked via scope validation (step-00 section 5c). Heuristics only serve as fallback in delegate mode when the PRD is incomplete.

**Why:** Code generation strategy drives CreateDto structure, service injection (ICodeGenerator<T>), and DI registration.

**Reference:** See `references/code-generation.md` for strategy table, volume-to-digits calculation, and backend patterns.



---

## Gap Analysis

Compare what EXISTS vs what the TASK REQUIRES:

```
For each element: EXISTS+COMPLETE → "skip" | EXISTS+INCOMPLETE → "modify" | MISSING → "create"
```

Cross-reference with step-00 challenge responses:
- Each entity: entity, EF config, service, controller, frontend pages → exists/missing
- Each section: NavigationSectionSeedData, frontend route → exists/missing
- If dependencies: verify FK target entities and their `?search=` support

### Seed Data Completeness Criteria (CRITICAL)

> **A seed file EXISTS does NOT mean it's COMPLETE.** When adding sections/resources to an existing module, seed files are the most commonly missed update.

For seed data files, apply these SPECIFIC completeness criteria:

| File | COMPLETE if | INCOMPLETE if |
|------|-------------|---------------|
| NavigationModuleSeedData.cs | Contains entries for ALL {sections} from step-00 scope | Missing GetSectionEntries/GetResourceEntries for ANY new section |
| Permissions.cs | Has constants for ALL {sections} (Read/Create/Update/Delete/Wildcard per section) | Missing permission constants for ANY new section |
| PermissionsSeedData.cs | Has HasData() entries for ALL permissions in Permissions.cs | Missing HasData() for ANY new permission |
| RolesSeedData.cs | Has role-permission mappings for ALL permissions | Missing mappings for ANY new permission |
| {App}SeedDataProvider.cs | Calls seed methods that cover ALL modules/sections | Missing calls for new module/section seed data |

**Decision matrix:**

```
Seed file NOT found                              → "create"
Seed file found + covers ALL target sections     → "skip"
Seed file found + MISSING some target sections   → "modify"  ← THIS IS THE COMMON MISS
```

> **ULTRA THINK:** When the task says "add absence management to HR module" and NavigationModuleSeedData.cs already has entries for "employees" section — the file EXISTS but is INCOMPLETE (missing "absences" section). Action = "modify", NOT "skip".

---

## Scope Re-Check (after exploration)

**Re-validate scope after code exploration reveals the true entity count.**
Step-00 guard uses the user's description (may undercount). Now we know the actual entities.

```
IF NOT delegate_mode:
  actual_entities = count of entities marked "create" in gap analysis
  actual_sections = count of sections marked "create"

  IF actual_entities > 6:
    WARNING: "Code exploration reveals {actual_entities} entities.
     This exceeds the recommended maximum (4) for a single /apex invocation.
     Risk: incomplete migrations, lost conventions, missing pages.
     Consider: split into {ceil(actual_entities/4)} iterations of ~4 entities each."

    Ask user to confirm or re-scope.
```

---

## Analysis Validation — User Checkpoint

**Objective:** Present findings and validate scope BEFORE planning.

### Present Findings

```
ANALYSIS FINDINGS
═══════════════════════════════════════════════════════════════

Entities expected / found / to create: {summary}
Sections expected / found / to create: {summary}
FK Relationships: {fkFields summary}
Dependencies: {cross-module refs or "none"}
Complexity: {module_complexity}
```

### Validate with User (if NOT auto_mode)

Question template (same as step-01 section 6b):
- "Scope is correct" (Recommended)
- "Add elements" → update entities/sections, re-run gap analysis
- "Reduce scope" → update accordingly
- "Change approach" → potentially restart from step-00

---

## Analysis Summary Output

```
**APEX SmartStack - Analysis Complete**

Navigation: {app_name} → {module_code} → {sections[].code}
Entities: {entity_name → create | modify | skip}
Existing: entities, configs, services, controllers, pages, seed data, tests (with paths)
Required: create / modify / skip lists
Profile: complexity, dependencies, FK fields, workflow, notifications
ACs: AC1..ACn (inferred from PRD/feature/task/challenge)
```
