# Embedded Signing Implementation Guide

## Overview

This document outlines the implementation of embedded Documenso signing for Port Nimara's Expression of Interest (EOI) documents. The system transforms the signing experience from external Documenso links to embedded signing within the Port Nimara website.

## Current Implementation Status

### ✅ Client Portal Changes (COMPLETED)

#### 1. Type Definitions Updated
- **File**: `utils/types.ts`
- **Added fields**:
  - `EmbeddedSignatureLinkClient?: string`
  - `EmbeddedSignatureLinkCC?: string`
  - `EmbeddedSignatureLinkDeveloper?: string`

#### 2. EOI Generation Enhanced
- **File**: `server/api/email/generate-eoi-document.ts`
- **Added URL transformation function**:
```typescript
const createEmbeddedSigningUrl = (documensoUrl: string, signerType: 'client' | 'cc' | 'developer'): string => {
  if (!documensoUrl) return '';
  const token = documensoUrl.split('/').pop();
  return `https://portnimara.com/sign/${signerType}/${token}`;
};
```

#### 3. Database Schema
- **Added NocoDB columns**:
  - `EmbeddedSignatureLinkClient`
  - `EmbeddedSignatureLinkCC`  
  - `EmbeddedSignatureLinkDeveloper`

#### 4. Configuration
- **File**: `.env.example`
- **Added webhook secret**: `WEBHOOK_SECRET_SIGNING=96BQQRiKkTIN2w0rHbqo7yHggV/sT8702HtHih3uNSY=`

## URL Structure

### Original Documenso URLs:
```
Client: https://signatures.portnimara.dev/sign/ABC123
CC: https://signatures.portnimara.dev/sign/DEF456
Developer: https://signatures.portnimara.dev/sign/GHI789
```

### New Embedded URLs:
```
Client: https://portnimara.com/sign/client/ABC123
CC: https://portnimara.com/sign/cc/DEF456
Developer: https://portnimara.com/sign/developer/GHI789
```

## Next Steps Required

### 🔄 Website Implementation (PENDING)

The Port Nimara website needs the following implementation:

#### 1. Install Documenso Embedding Package
```bash
npm install @documenso/embed-vue
```

#### 2. Create Dynamic Route
**File**: `pages/sign/[type]/[token].vue`

#### 3. Implement Signing Pages
- Main signing page with embedded interface
- Success page (`pages/sign/success.vue`)
- Error page (`pages/sign/error.vue`)

#### 4. Technical Specifications
- **Framework**: Nuxt 3 with Vue 3
- **Styling**: Tailwind CSS
- **Documenso Host**: `https://signatures.portnimara.dev`
- **Brand Colors**: `#0056b3` (primary), `#ffffff`, `#f8f9fa`
- **Logos**: `/images/logo-full.png`, `/images/logo-no-text.png`

### 🔄 CORS Configuration (MANUAL)

Add to nginx config for `signatures.portnimara.dev`:

```nginx
location / {
    # CORS headers for embedding
    add_header 'Access-Control-Allow-Origin' 'https://portnimara.com' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    
    # Handle preflight requests
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' 'https://portnimara.com' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
}
```

## Testing Strategy

### Phase 1: Basic Functionality
1. Generate a test EOI in client portal
2. Verify both URL sets are populated in database
3. Test embedded URLs manually
4. Verify CORS headers are working

### Phase 2: End-to-End Testing
1. Create interest
2. Generate EOI
3. Complete signing via embedded interface
4. Verify status updates in client portal

### Phase 3: Email Integration
1. Update email templates to use embedded URLs
2. Test email delivery with embedded links
3. Monitor completion rates

## Implementation Details for Website Team

### Required Environment Variables
```env
WEBHOOK_SECRET_SIGNING=96BQQRiKkTIN2w0rHbqo7yHggV/sT8702HtHih3uNSY=
```

### Signer Type Messaging
```javascript
const signerMessages = {
  client: {
    title: 'Sign Your Expression of Interest',
    subtitle: 'Please review and sign your Port Nimara berth EOI'
  },
  cc: {
    title: 'Approve Expression of Interest',
    subtitle: 'Please review and approve this Port Nimara berth EOI'
  },
  developer: {
    title: 'Review and Sign Expression of Interest',
    subtitle: 'Please review and sign this Port Nimara berth EOI'
  }
};
```

### Token Validation
- Validate signer type: `['client', 'cc', 'developer'].includes(signerType)`
- Validate token format: `/^[a-zA-Z0-9_-]+$/`
- Redirect to error page for invalid tokens

### Webhook Integration (Optional - Phase 2)
```javascript
// Endpoint: https://client-portal.portnimara.com/api/webhook/document-signed
// Method: POST
// Headers: { 'x-webhook-secret': '96BQQRiKkTIN2w0rHbqo7yHggV/sT8702HtHih3uNSY=' }
// Body: { token, signerType, signedAt }
```

## Current Data Flow

### Document Generation:
1. Client Portal generates EOI via Documenso API
2. Receives original signing URLs from Documenso
3. Transforms URLs to embedded format
4. Stores both original and embedded URLs in NocoDB

### Database Example:
```json
{
  "Signature Link Client": "https://signatures.portnimara.dev/sign/ABC123",
  "EmbeddedSignatureLinkClient": "https://portnimara.com/sign/client/ABC123",
  "Signature Link CC": "https://signatures.portnimara.dev/sign/DEF456",
  "EmbeddedSignatureLinkCC": "https://portnimara.com/sign/cc/DEF456",
  "Signature Link Developer": "https://signatures.portnimara.dev/sign/GHI789",
  "EmbeddedSignatureLinkDeveloper": "https://portnimara.com/sign/developer/GHI789"
}
```

## Rollback Strategy

If issues arise:
1. **Immediate**: Change email templates back to original URLs
2. **Database**: Original URLs remain intact for fallback
3. **Website**: Can redirect embedded routes to Documenso temporarily

## Success Metrics

- ✅ Embedded signing works for all signer types
- ✅ Status tracking continues working identical to current system
- ✅ Mobile responsive interface
- ✅ No increase in signing error rates
- ✅ Improved user experience (staying on portnimara.com domain)

## Contact Information

- **Webhook Secret**: `96BQQRiKkTIN2w0rHbqo7yHggV/sT8702HtHih3uNSY=`
- **Documenso Instance**: `https://signatures.portnimara.dev`
- **Development Server**: `http://localhost:3000` (client portal)

---

*Implementation completed: Client Portal phase*  
*Next: Website implementation and CORS configuration*
