# Office 365 Add-ins - Document Tagger & Email Validator

A comprehensive solution for scanning, tagging, and validating Office documents (Word & Excel) with automatic content detection and Outlook integration to prevent sending untagged files.

## Features

### Word Add-in
- Login authentication with JWT token
- Content scanning with regex pattern matching
- Automatic tag detection for:
  - Confidential information
  - Financial data
  - Personal data (SSN, passport, etc.)
  - Email addresses
  - Phone numbers
  - IP addresses
  - URLs
  - Credit card numbers
  - Dates
- Visual tagging interface
- Document status tracking
- Server synchronization

### Excel Add-in
- Same authentication and scanning features as Word
- Scans all sheets in workbook
- Detects sensitive data across multiple worksheets
- Batch processing of cell content
- Sheet-by-sheet reporting

### Outlook Add-in
- Validates attachments before sending
- Blocks sending emails with untagged Word/Excel files
- Manual attachment validation
- Integration with backend API
- User-friendly error messages

## Architecture

```
office-addins/
├── shared/
│   ├── auth-service.js         # JWT authentication service
│   └── tagging-service.js      # Content scanning & tagging
├── word/
│   ├── manifest.xml            # Word add-in manifest
│   ├── taskpane.html          # Word UI
│   └── taskpane.js            # Word logic
├── excel/
│   ├── manifest.xml            # Excel add-in manifest
│   ├── taskpane.html          # Excel UI
│   └── taskpane.js            # Excel logic
└── outlook/
    ├── manifest.xml            # Outlook add-in manifest
    └── commands.html           # Outlook event handlers
```

## Installation

### Prerequisites
- Node.js (v14 or higher)
- Office 365 subscription
- Access to https://145.223.82.98:8484/login endpoint

### Setup Steps

1. **Host the Add-in Files**
   ```bash
   # Install a local web server
   npm install -g http-server
   
   # Navigate to the add-ins directory
   cd office-addins
   
   # Start the server with CORS enabled
   http-server -p 3000 --cors
   ```

2. **For Production Deployment**
   - Host files on a web server with HTTPS
   - Update all URLs in manifest files from `https://localhost:3000` to your production URL
   - Ensure CORS is properly configured on your server

3. **Install Add-ins in Office**

   **For Word & Excel:**
   - Open Word or Excel
   - Go to Insert > Add-ins > My Add-ins
   - Click "Upload My Add-in"
   - Browse and select the appropriate manifest.xml file
   - The add-in will appear in the Home ribbon

   **For Outlook:**
   - Open Outlook Web or Desktop
   - Go to File > Manage Add-ins (Desktop) or Settings > View all Outlook settings > Mail > Customize actions (Web)
   - Click "Add from file"
   - Upload the outlook/manifest.xml file

## Configuration

### Backend API Endpoints Required

Your backend at `https://145.223.82.98:8484` should implement:

1. **POST /login**
   ```json
   Request:
   {
     "username": "user@example.com",
     "password": "password123"
   }
   
   Response:
   {
     "token": "eyJhbGciOiJIUzI1NiIs...",
     "user": {
       "username": "user@example.com",
       "name": "John Doe"
     }
   }
   ```

2. **POST /api/document-tags**
   ```json
   Request:
   {
     "documentName": "Report.docx",
     "tags": [
       {
         "name": "CONFIDENTIAL",
         "count": 3,
         "priority": 1
       }
     ],
     "timestamp": "2025-01-15T10:30:00Z"
   }
   
   Response:
   {
     "success": true,
     "documentId": "doc123"
   }
   ```

3. **POST /api/check-attachments**
   ```json
   Request:
   {
     "files": ["Document1.docx", "Spreadsheet1.xlsx"]
   }
   
   Response:
   {
     "allTagged": false,
     "untaggedFiles": ["Document1.docx"]
   }
   ```

### Customizing Regex Patterns

Edit `shared/tagging-service.js` to add or modify patterns:

```javascript
taggingService.addPattern(
    'CUSTOM_PATTERN',           // Tag name
    /your-regex-here/gi,        // Regex pattern
    '#FF0000',                  // Color
    1                           // Priority (1=highest)
);
```

## Usage

### Word/Excel Add-ins

1. **Login**
   - Open the add-in from the ribbon
   - Enter credentials for https://145.223.82.98:8484/login
   - JWT token is stored securely

2. **Scan Document**
   - Click "Scan Document Content" or "Scan All Sheets"
   - Add-in analyzes content with regex patterns
   - Tags are automatically detected and displayed
   - Document is marked as tagged

3. **View Tags**
   - See all detected tags with match counts
   - Color-coded by severity
   - Tags persist with the document

### Outlook Add-in

1. **Automatic Validation**
   - Compose an email with Word/Excel attachments
   - Click Send
   - Add-in automatically checks if files are tagged
   - Blocks send if untagged files are detected

2. **Manual Check**
   - Click "Check Attachments" button in ribbon
   - See immediate feedback on attachment status
   - Get list of untagged files

## Security Features

### JWT Token Storage
- Tokens stored in Office.context.roamingSettings
- Automatic token expiration handling
- Secure logout clears all credentials

### Content Detection
- Detects 9 types of sensitive information
- Priority-based tagging system
- No content sent to server (only tags)

### Email Protection
- Prevents accidental data leaks
- Server-side verification
- User-friendly error messages

## Troubleshooting

### Login Issues
- **Problem:** "Authentication failed"
- **Solution:** Verify backend is running at https://145.223.82.98:8484
- Check CORS configuration allows requests from add-in domain

### Scanning Not Working
- **Problem:** "Error scanning document"
- **Solution:** 
  - Ensure you're logged in
  - Check document has content
  - Verify Office.js is loaded

### Outlook Blocking Not Working
- **Problem:** Emails send with untagged files
- **Solution:**
  - Verify Outlook add-in is installed correctly
  - Check that ItemSend event is registered in manifest
  - Ensure backend /api/check-attachments endpoint is working

### Add-in Not Loading
- **Problem:** Add-in doesn't appear in ribbon
- **Solution:**
  - Clear Office cache: Delete `%LOCALAPPDATA%\Microsoft\Office\16.0\Wef\`
  - Reload Office application
  - Verify manifest.xml is valid

## API Reference

### AuthService

```javascript
// Login
const result = await authService.login(username, password);

// Check authentication
const isAuth = authService.isAuthenticated();

// Get token
const token = authService.getToken();

// Logout
await authService.logout();

// Make authenticated request
const response = await authService.apiRequest('/api/endpoint', {
    method: 'POST',
    body: JSON.stringify(data)
});
```

### TaggingService

```javascript
// Scan content
const tags = taggingService.scanContent(textContent);

// Apply tags to document
await taggingService.applyTagsToDocument(tags, 'word');

// Check if document is tagged
const isTagged = taggingService.isDocumentTagged();

// Get document tags
const tagData = taggingService.getDocumentTags();

// Sync with server
await taggingService.syncTagsWithServer(documentName, tags);
```

## Development

### Adding New Tag Patterns

1. Edit `shared/tagging-service.js`
2. Add pattern to `initializePatterns()`:
   ```javascript
   {
       name: 'YOUR_TAG',
       pattern: /regex-pattern/gi,
       color: '#HEXCOLOR',
       priority: 1-4
   }
   ```

### Building for Production

1. Update all URLs in manifest files
2. Enable HTTPS on your web server
3. Test all endpoints with production backend
4. Deploy files to production server
5. Distribute manifest files to users

## Testing

### Manual Testing Checklist

**Word/Excel:**
- [ ] Login with valid credentials
- [ ] Login with invalid credentials (should fail)
- [ ] Scan document with sensitive content
- [ ] Scan document with no sensitive content
- [ ] Verify tags persist after closing and reopening
- [ ] Test logout functionality

**Outlook:**
- [ ] Send email with no attachments (should send)
- [ ] Send email with non-Office attachments (should send)
- [ ] Send email with tagged Office files (should send)
- [ ] Send email with untagged Office files (should block)
- [ ] Use manual "Check Attachments" button

## License

[Your License Here]

## Support

For issues or questions:
- Email: support@yourcompany.com
- Documentation: [Your docs URL]

## Version History

### v1.0.0 (2025-01-15)
- Initial release
- Word add-in with content scanning
- Excel add-in with multi-sheet scanning
- Outlook add-in with send blocking
- JWT authentication
- 9 default tag patterns
