# PDF Template Test Hints

## Test Structure

### Basic Setup
```typescript
import { test, expect } from '@playwright/test';
import { LoginPage } from '../../../../pages/login.page';
import { DashboardMainPage } from '../../../../pages/dashboard-main.page';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as path from 'path';  // For file operations

dotenv.config();
test.setTimeout(10 * 60 * 1000);

test('@pdf-templates REG-00X: Test description', async ({ page }) => {
  const loginPage = new LoginPage(page);
  const dashboardPage = new DashboardMainPage(page);
  
  const testEmail = process.env.TEST_EMAIL || 'cdp@hy.ly';
  const testPassword = process.env.TEST_PASSWORD || 'BMy2L1rRXZlkKoTU7';
});
```

## Test Categories

### 1. Template Creation (REG-005)
- Creating new PDF templates
- Saving and naming templates
- Setting template properties

### 2. Template Annotation (REG-004)
- Freezing template state
- Adding annotations
- Saving annotated templates

## Critical Selectors and Patterns

### PDF Templates Navigation
```typescript
// MANDATORY: Very long wait time before clicking
await page.waitForTimeout(50000); // Critical for sidebar stability (increased from 40s)

// Try multiple selector approaches in order
1. page.getByRole('button', { name: 'PDF Templates' })
2. page.getByText('PDF Templates', { exact: true })
3. page.getByText('PDF Template', { exact: false })  // Without 's'
4. page.getByRole('button', { name: 'Templates' })
5. page.locator('*:has-text("PDF")').first()  // Last resort

// REQUIRED: Throw error if not found
if (!pdfTemplatesClicked) {
  throw new Error('PDF Templates button not found in sidebar');
}
```

### Dialog/Page Verification
```typescript
// Check if PDF Templates opened (try both dialog and URL)
const pdfTemplatesDialog = page.locator('dialog:has-text("PDF Template"), [role="dialog"]:has-text("PDF Template")');
const dialogVisible = await pdfTemplatesDialog.isVisible({ timeout: 3000 });

// Also check URL change
if (currentUrl.includes('pdf') || currentUrl.includes('template')) {
  // Successfully navigated to PDF Templates
}

// REQUIRED: Throw error if not opened
if (!pdfTemplatesOpened) {
  throw new Error('PDF Templates dialog/page did not open');
}
```

### Template Creation Flow
```typescript
// Expand My PDF Template section
const myPdfTemplate = page.getByText('My PDF Template', { exact: true });
// MUST throw error if not found

// Open existing template or create new
const existingTemplate = page.getByText('Open any existing pdf template');
// OR
const newPdfTemplate = page.getByText('New PDF Template', { exact: true });
// MUST throw error if not found
```

### Freeze/Lock Implementation
```typescript
// Try multiple freeze methods in priority order
1. page.locator('button:has-text("Freeze")').first()
2. page.locator('button:has-text("Lock")').first()
3. page.locator('button:has-text("Finalize")').first()
4. page.locator('[data-testid*="freeze"]').first()
5. page.locator('[data-testid*="edit-mode"]').first()  // Toggle edit mode
6. page.locator('[aria-label*="lock"], .lock-icon').first()

// Confirm freeze if dialog appears
const confirmButton = page.locator('button:has-text("Confirm"), button:has-text("Yes"), button:has-text("OK")').first();
```

### Annotation Requirements
```typescript
// MANDATORY: Wait before annotations
await page.waitForTimeout(8000);

// Annotation button selector
const annotateButton = page.locator('button:has-text("Add Annotations")').first();

// REQUIRED: Throw error if not found
if (!annotateVisible) {
  throw new Error('Annotation button not found');
}
```

### Save Template
```typescript
// Try multiple save options
1. page.locator('button:has-text("Lock Annotation")').first()
2. page.locator('button:has-text("Save Template")').first()
3. page.locator('button:has-text("Save")').first()
4. page.locator('[data-testid*="save"]').first()

// Check for error messages after save
const errorMessage = page.locator('text=/Error|Failed/i').first();
if (await errorMessage.isVisible()) {
  throw new Error('Failed to save template');
}
```

### PDF Export via Share Button
```typescript
// Step 1: Click Share button
const shareButton = page.getByText('Share', { exact: true });
// MUST throw error if not found

// Step 2: Click Download PDF in dropdown
const downloadPdfOption = page.getByText('Download PDF', { exact: true });
await downloadPdfOption.click();

// Step 3: Wait for side panel
await page.waitForTimeout(2000);

// Step 4: Click second Download PDF button in panel
const downloadButton = page.getByText('Download PDF', { exact: true }).nth(1);
// OR use fallback
const altDownloadButton = page.locator('button:has-text("Download PDF")').last();
```

## Required Test Structure

### Test Configuration
- **MANDATORY**: `test.setTimeout(10 * 60 * 1000)`
- **REQUIRED**: Generate unique dashboard name for templates
- **CRITICAL**: Use environment variables for credentials

### Import Requirements
```typescript
import { test, expect } from '@playwright/test';
import { LoginPage } from '../../pages/login.page';
import { DashboardMainPage } from '../../pages/dashboard-main.page';
import * as dotenv from 'dotenv';
```

## Wait Time Requirements
- Before PDF Templates click: 40 seconds (CRITICAL)
- After clicking PDF Templates: 5 seconds
- After expanding My PDF Template: 2 seconds
- After creating new template: 3 seconds
- Before adding annotations: 8 seconds
- After clicking Share: 1 second
- After Download PDF dropdown: 2 seconds

## Validation Requirements
1. **MUST** verify PDF Templates opened (dialog or URL)
2. **MUST** verify My PDF Template section exists
3. **MUST** verify freeze/lock action taken
4. **MUST** verify annotation button found
5. **MUST** verify Share button exists
6. **MUST** verify PDF downloads with size > 0

## Common Issues to Avoid
- **DON'T** skip the 40-second wait before clicking PDF Templates
- **DON'T** ignore error throwing - test must fail if actions don't complete
- **DON'T** forget to click second Download PDF button in side panel
- **DON'T** skip download validation and cleanup

## Expected Flow
1. Login → Dashboard loads
2. Wait 40 seconds for full stabilization
3. Click PDF Templates (try multiple selectors)
4. Verify dialog/page opened
5. Expand My PDF Template
6. Open existing template or create new
7. Apply freeze/lock status
8. Wait 8 seconds, then add annotations
9. Save template
10. Click Share → Download PDF → Download button in panel
11. Verify PDF downloads successfully
12. Clean up test file

## Error Handling Requirements
Each major action MUST throw an error if it fails:
- PDF Templates not found → throw error
- Dialog/page didn't open → throw error
- My PDF Template not found → throw error
- New PDF Template not found → throw error
- No freeze action available → throw error
- Annotation button not found → throw error
- Share button not found → throw error
- Download PDF not in dropdown → throw error
- PDF download failed → throw error

## Success Criteria
- PDF Templates opens successfully
- Template created/opened
- Freeze/lock status applied
- Annotations added
- Template saved
- PDF downloaded via Share button
- File size > 0
- Test completes within 10 minutes