# Domain Templates

The domain templates allow creating or updating existing data domains from a template. Templates follow the Domain-Driven Design (DDD) principles and provide pre-built business domain structures that users can instantiate or extend.

## Organization by Industry Verticals

Templates are organized by industry verticals to provide better categorization and discovery:

- **Business Services**: E-commerce, Financial Services, Legal Services
- **Healthcare & Life Sciences**: Healthcare, Pharmaceutical, Research  
- **Education & Training**: Education, Corporate Training, Certification
- **Real Estate & Construction**: Real Estate, Construction, Property Management
- **Manufacturing & Logistics**: Manufacturing, Supply Chain, Distribution
- **Technology & Media**: Gaming, IoT, Content Management, Social Media
- **Public Sector**: Government, Non-Profit, Healthcare

See `verticals/README.md` for detailed information about the vertical organization.

## Template Structure

Each template is a TypeScript file that exports a default function conforming to the template signature. Templates create comprehensive data domains with proper namespace organization, entity relationships, and semantic annotations.

### Required Function Signature

```typescript
import type { CreateTemplateOptions } from './types.js'
import { DataDomain } from '../DataDomain.js'

export default function createMyDomain(options: CreateTemplateOptions = {}): DataDomain {
  // Template implementation
}
```

### Template Implementation Pattern

```typescript
/**
 * Template Documentation Header
 * 
 * Provide comprehensive documentation explaining:
 * - What business domain this template models
 * - Key entities and relationships included
 * - Semantic annotations and business rules applied
 * - Example usage scenarios
 */

import { DataDomain } from '../DataDomain.js'
import { SemanticType } from '../Semantics.js'
import {
  addIdField,
  addNameField,
  addEmailField,
  // Import other helper functions as needed
} from '../helpers/Intelisense.js'
import type { CreateTemplateOptions } from './types.js'

function createDomain(): DataDomain {
  return new DataDomain({
    info: {
      name: 'My Business Domain',
      displayName: 'My Business Domain',
      description: 'Clear description of what this domain models',
    },
  })
}

export default function createMyDomain(options: CreateTemplateOptions = {}): DataDomain {
  // Use existing domain if provided, otherwise create new one
  const domain = options.domain ?? createDomain()
  
  // Create namespaces following business capabilities
  const coreNamespace = domain.addNamespace({ 
    info: { name: 'CoreManagement' } 
  })
  
  // Add models to organize related entities
  const entityModel = coreNamespace.addModel({ 
    info: { name: 'CoreEntities' } 
  })
  
  // Create entities with proper semantic annotations
  const mainEntity = entityModel.addEntity({ 
    info: { name: 'MainEntity' },
    semantics: [{ type: SemanticType.User }] // If applicable
  })
  
  // Add properties using helper functions for consistency
  addIdField(mainEntity)
  addNameField(mainEntity)
  addEmailField(mainEntity)
  
  // Add custom properties with proper semantics
  mainEntity.addProperty({
    info: { name: 'customField' },
    type: 'string',
    required: false,
    semantics: [/* appropriate semantics */]
  })
  
  // Create associations between entities
  // (Add more entities and relationships as needed)
  
  return domain
}
```

## Adding a Template

### 1. Create the Template File

Create a new file `[domain-name]-domain.ts` in `src/modeling/templates/` following the naming convention:

- Use kebab-case for file names
- End with `-domain.ts`
- Examples: `healthcare-domain.ts`, `financial-services-domain.ts`

### 2. Follow Modeling Guidelines

Templates must adhere to the modeling instructions in `.github/instructions/modeling.instructions.md`:

- **Business-First Approach**: Model business concepts, not technical concerns
- **Proper Hierarchy**: DataDomain → DomainNamespace → DomainModel → DomainEntity → DomainProperty
- **Semantic Annotations**: Use `SemanticType` for passwords, emails, timestamps, etc.
- **Security**: Mark sensitive properties as `writeOnly`, validate all inputs
- **Database Compliance**: Follow PostgreSQL naming conventions (snake_case conversion)

### 3. Required Imports

Include these essential imports:

```typescript
import { DataDomain } from '../DataDomain.js'
import { SemanticType } from '../Semantics.js'
import type { CreateTemplateOptions } from './types.js'

// Import semantic definition helpers as needed
import { createCalculatedSemantic } from '../definitions/Calculated.js'
import { createCurrencySemantic } from '../definitions/Currency.js'

// Import property helper functions for consistency
import {
  addIdField,
  addNameField,
  addEmailField,
  addPasswordField,
  addCreatedAtField,
  addUpdatedAtField,
  // ... other helpers as needed
} from '../helpers/Intelisense.js'
```

### 4. Handle Template Options

Always support the `CreateTemplateOptions` interface:

```typescript
export default function createMyDomain(options: CreateTemplateOptions = {}): DataDomain {
  // Use provided domain or create new one
  const domain = options.domain ?? createDomain()
  
  // If domain is provided, you're extending an existing domain
  // If not provided, you're creating a new domain
  
  return domain
}
```

## Registering Templates

### 1. Add to Generation Script

Edit `scripts/generate-template-metadata.js` and add your template to the registry:

```javascript
// Import your template function
import createMyDomain from '../build/src/modeling/templates/my-domain.js'

// Add to templates array
const TEMPLATE_CONFIGS = [
  {
    id: 'my-business-domain',
    name: 'My Business Domain',
    description: 'Brief description for UI display',
    version: '1.0.0',
    author: 'API Now! Core Team',
    tags: ['business', 'industry-specific'], // For categorization
    createdAt: '2025-01-01T00:00:00.000Z',
    updatedAt: '2025-01-01T00:00:00.000Z',
    createDomainFn: createMyDomain,
  },
  // ... other templates
]
```

### 2. Template Metadata

The generation script will create metadata including:

- Template structure analysis (namespaces, models, entities)
- Property counts and types
- Association mappings
- Semantic annotation usage
- UI presentation information

## Generating Metadata

Each template needs to be processed to generate metadata files. These metadata are used to generate the templates view in the UI.

**If you won't generate metadata, the template won't get registered by the UI.**

### 1. Build the Project First

```sh
npm run build
```

### 2. Run the Metadata Generation Script

```sh
node scripts/generate-template-metadata.js
```

### 3. Rebuild to Include New Metadata

```sh
npm run build
```

All metadata are generated under `src/modeling/templates/meta` directory as JSON files.

## Best Practices

### Domain Design

1. **Business Alignment**: Model actual business processes and entities
2. **Clear Naming**: Use business-meaningful names, not technical jargon
3. **Proper Grouping**: Organize entities into logical namespaces and models
4. **Semantic Richness**: Apply appropriate semantic annotations for security and behavior

### Code Quality

1. **Documentation**: Include comprehensive JSDoc comments explaining the business purpose
2. **Type Safety**: Use TypeScript interfaces and proper type annotations
3. **Error Handling**: Validate inputs and provide clear error messages
4. **Consistency**: Use helper functions from `helpers/Intelisense.js` for common patterns

### Security

1. **Sensitive Data**: Mark passwords and sensitive fields as `writeOnly`
2. **Validation**: Validate all user inputs and model structures
3. **Access Control**: Consider data access patterns in your domain design

## Example Templates

Refer to existing templates for comprehensive examples:

- `ecommerce-domain.ts` - E-commerce platform with users, products, orders
- `blog-domain.ts` - Content management with publishing workflow

These demonstrate proper structure, semantic usage, and business modeling patterns.
