# Codebase Structure

**Analysis Date:** 2026-04-02

## Directory Layout

```
Sharepoint-Toolbox/
├── .planning/                          # GSD planning documentation
├── .git/                               # Git repository
├── .gitea/                             # Gitea configuration
├── .claude/                            # Claude IDE configuration
├── examples/                           # CSV example files for bulk operations
│   ├── bulk_add_members.csv            # Template: add users to groups
│   ├── bulk_create_sites.csv           # Template: create multiple sites
│   ├── bulk_transfer.csv               # Template: transfer site ownership
│   └── folder_structure.csv            # Template: create folder hierarchies
├── lang/                               # Language/localization files
│   └── fr.json                         # French language translations
├── Sharepoint_ToolBox.ps1              # Main application (6408 lines)
├── Sharepoint_Settings.json            # User settings (data folder, language preference)
├── Sharepoint_Export_profiles.json     # Saved connection profiles (generated at runtime)
├── Sharepoint_Templates.json           # Saved site templates (generated at runtime)
├── README.md                           # Documentation and feature overview
├── TODO.md                             # Future feature roadmap
└── SPToolbox-logo.png                  # Application logo
```

## Directory Purposes

**`examples/`:**
- Purpose: Reference CSV templates for bulk operations
- Contains: CSV example files demonstrating column structure for bulk tasks
- Key files:
  - `bulk_add_members.csv`: User email and group name mappings
  - `bulk_create_sites.csv`: Site title, URL, type, language
  - `bulk_transfer.csv`: Source site, target owner email
  - `folder_structure.csv`: Folder paths to create under libraries
- Non-versioned: May contain user data after operations
- Access: Referenced by bulk operation dialogs; templates shown in UI

**`lang/`:**
- Purpose: Store language packs for UI localization
- Contains: JSON files with key-value pairs for UI text
- Key files:
  - `fr.json`: Complete French translations for all UI elements, buttons, messages
- Naming: `<language-code>.json` (e.g., `en.json`, `fr.json`)
- Loading: `Load-Language` function (line 2933) reads and caches translation dict
- Integration: `T("key")` function (line 2908) looks up translations at runtime

**`.planning/`:**
- Purpose: GSD (GitHub Sync & Deploy) planning and analysis documents
- Contains: Generated documentation for architecture, structure, conventions, concerns
- Generated: By GSD mapping tools; not manually edited
- Committed: Yes, tracked in version control

## Key File Locations

**Entry Points:**

- `Sharepoint_ToolBox.ps1` (lines 1-6408): Single monolithic PowerShell script
  - Execution: `.ps1` file run directly or sourced from PowerShell ISE/terminal
  - Initialization: Lines 6386-6408 load settings, language, profiles, then show main form
  - Exit: Triggered by form close or exception; automatic cleanup of runspaces

- Main GUI Form instantiation: `Sharepoint_ToolBox.ps1` line 2992
  - Creates WinForms.Form object
  - Registers all event handlers
  - Shows dialog via `[void]$form.ShowDialog()` at line 6405

**Configuration:**

- `Sharepoint_Settings.json`: User preferences
  - Structure: `{ "dataFolder": "...", "lang": "en" }`
  - Loaded by: `Load-Settings` (line 136)
  - Saved by: `Save-Settings` (line 147)
  - Auto-created: If missing, defaults to English + script root directory

- `Sharepoint_Export_profiles.json`: Connection profiles (auto-created)
  - Structure: `{ "profiles": [ { "name": "Prod", "clientId": "...", "tenantUrl": "..." }, ... ] }`
  - Loaded by: `Load-Profiles` (line 57)
  - Saved by: `Save-Profiles` (line 68)
  - Location: Determined by `Get-ProfilesFilePath` (line 50) - same as settings

- `Sharepoint_Templates.json`: Captured site templates (auto-created)
  - Structure: `{ "templates": [ { "name": "...", "libraries": [...], "groups": [...], ... }, ... ] }`
  - Loaded by: `Load-Templates` (line 484)
  - Saved by: `Save-Templates` (line 495)
  - Location: Same folder as profiles/settings

**Core Logic:**

- Permissions Report: `Sharepoint_ToolBox.ps1` lines 1784-2001
  - `Generate-PnPSitePermissionRpt` (line 1852): Main permission scanning function
  - `Get-PnPWebPermission` (line 1944): Recursive site/subsite scanning
  - `Get-PnPListPermission` (line 1912): Library and list enumeration
  - `Get-PnPFolderPermission` (line 1882): Folder-level permission scanning
  - `Get-PnPPermissions` (line 1786): Individual role assignment extraction

- Storage Metrics: `Sharepoint_ToolBox.ps1` lines 2002-2110
  - `Get-SiteStorageMetrics` (line 2004): Main storage scan function
  - Nested `Collect-FolderStorage` (line 2010): Recursive folder traversal
  - Nested `Collect-WebStorage` (line 2034): Per-web storage collection

- File Search: `Sharepoint_ToolBox.ps1` lines 2112-2233
  - Search API integration via PnP.PowerShell
  - KQL (Keyword Query Language) filter construction
  - Client-side regex filtering after API retrieval

- Template Management: `Sharepoint_ToolBox.ps1` lines 475-1360
  - `Show-TemplateManager` (line 542): Template dialog
  - Capture state machine in dialog event handlers
  - Template persistence via JSON serialization

- Duplicate Detection: `Sharepoint_ToolBox.ps1` lines 2235-2408
  - File mode: Search API with grouping by filename
  - Folder mode: Direct library enumeration + comparison
  - HTML export with grouped UI

**Testing:**

- No automated test framework present
- Manual testing via GUI interaction
- Examples folder (`examples/`) provides test data templates

**Localization:**

- `lang/fr.json`: French translations
  - Format: JSON object with `"_name"` and `"_code"` metadata + translation keys
  - Loading: `Load-Language` (line 2933) parses JSON into `$script:LangDict`
  - Usage: `T("key")` replaces hardcoded English strings with translations
  - UI Update: `Update-UILanguage` (line 2951) updates all registered controls

## Naming Conventions

**Files:**

- Main application: `Sharepoint_ToolBox.ps1` (PascalCase with underscore separator)
- Settings/data: `Sharepoint_<Type>.json` (e.g., `Sharepoint_Settings.json`)
- Generated exports: `<Report>_<site>_<timestamp>.<format>` or `<Report>_<mode>_<timestamp>.<format>`
  - Permissions: `Permissions_<site>_<yyyyMMdd_HHmmss>.csv/html`
  - Storage: `Storage_<site>_<yyyyMMdd_HHmmss>.csv/html`
  - Search: `FileSearch_<yyyyMMdd_HHmmss>.csv/html`
  - Duplicates: `Duplicates_<mode>_<yyyyMMdd_HHmmss>.csv/html`
- Language files: `<language-code>.json` (lowercase, e.g., `fr.json`)
- Example files: `<operation>_<type>.csv` (lowercase with underscore, e.g., `bulk_add_members.csv`)

**PowerShell Functions:**

- Public functions: `Verb-Noun` naming (e.g., `Generate-PnPSitePermissionRpt`, `Get-SiteStorageMetrics`)
- Private/internal functions: Prefixed with `_` or grouped in regions (e.g., `_Pkl-Sort`, `_Pkl-Repopulate`)
- Event handlers: Declared inline in `.Add_Click` or `.Add_TextChanged` blocks; not named separately
- Nested functions (inside others): CamelCase with parent context (e.g., `Collect-FolderStorage` inside `Get-SiteStorageMetrics`)

**Variables:**

- Script-scope state: `$script:<name>` (e.g., `$script:AllPermissions`, `$script:DataFolder`)
- Local function scope: camelCase (e.g., `$result`, `$dlg`, `$lists`)
- Control references: descriptive with type suffix (e.g., `$txtClientId`, `$btnPermRun`, `$cboProfile`)
- Control variables stored in script scope: Prefixed `$script:` for access across event handlers
- Temporary arrays: `$<plural>` (e.g., `$sites`, `$folders`, `$results`)

**Types:**

- Region markers: `#region ===== <Name> =====` (e.g., `#region ===== GUI =====`)
- Comments: Double hash for section comments (e.g., `# ── Label helper ──`)

**Exports:**

- HTML: Class names like `permission-table`, `storage-tree`, `duplicate-group`
- CSV: Column headers match object property names (e.g., `Title`, `URL`, `Permissions`)

## Where to Add New Code

**New Feature:**

1. Create a new region section in `Sharepoint_ToolBox.ps1`:
   ```powershell
   #region ===== [Feature Name] =====
   function [Verb]-[Feature](...) { ... }
   #endregion
   ```

2. Primary code locations:
   - Core logic: After line 2408 (after duplicates region, before Transfer region)
   - PnP interaction: Own `#region` mirroring storage/permissions pattern
   - HTML export helper: Create function like `Export-[Feature]ToHTML` in dedicated region

3. Add UI tab or button:
   - Create new TabPage in `$tabs` (around line 3113+)
   - Register event handler for execution button in Event Handlers region (line 4068+)
   - Add label in French translation file (`lang/fr.json`)

4. Add menu item if needed:
   - Modify MenuStrip construction around line 3001-3027
   - Register handler in Event Handlers region

5. Persist settings:
   - Add properties to `Sharepoint_Settings.json` structure
   - Update `Load-Settings` (line 136) to include new fields
   - Update `Save-Settings` (line 147) to serialize new fields

**New Component/Module:**

- Keep as internal functions (no separate files)
- If complexity exceeds 500 lines, consider refactoring into regions
- Pattern: All code stays in single `Sharepoint_ToolBox.ps1` file
- Dependencies: Use script-scope variables for shared state

**Utilities:**

- Shared helpers: `Shared Helpers` region (line 4-46)
  - Add new helper function here if used by multiple features
  - Examples: `Write-Log`, `Format-Bytes`, `EscHtml`, `Validate-Inputs`

- UI control factories: Lines 3119-3146
  - Add new `New-<Control>` helper for frequently used UI patterns
  - Examples: `New-Group`, `New-Check`, `New-Radio`, `New-ActionBtn`

- Internationalization: `Internationalization` region (line 2732-2989)
  - Add new translation keys to `lang/fr.json`
  - Update `T()` function if new resolution logic needed

## Special Directories

**`examples/`:**
- Purpose: CSV templates for user reference
- Generated: No; committed as examples
- Committed: Yes, tracked in version control
- Accessed by: Bulk operation dialogs (not directly imported by code; users download manually)
- Content: Non-executable; user-facing documentation

**`.planning/`:**
- Purpose: GSD-generated codebase analysis and planning documents
- Generated: Yes; created by GSD mapping tools during `/gsd:map-codebase`
- Committed: Yes; documents are version-controlled
- Accessed by: `/gsd:plan-phase` and `/gsd:execute-phase` commands for context
- Content: Markdown documents describing architecture, structure, conventions, concerns, stack, integrations

**Generated Files (Runtime):**

Files created at runtime, not part of initial repository:
- `Sharepoint_Export_profiles.json`: User-created connection profiles
- `Sharepoint_Templates.json`: User-captured site templates
- Export reports: `*_<timestamp>.(csv|html)` files in output folder (default: script root or user-selected)

---

*Structure analysis: 2026-04-02*
