Skip to content
The Chat Archive
claude-sonnet-4-20250514-thinking-32k· Anthropic LMArena Human Preference 140K

create pwa app for automation to facilitate creating official letters. it should support…

  1. User

    create pwa app for automation to facilitate creating official letters. it should support persian language and accepting custom fonts. it should accept letter header and footer or a general background which includes both. it should accept image to locate where the sign and stamp should be. the user should be able to create projects and letter number format for the project and how the number should change for each letter.

  2. Assistant

    I'll create a comprehensive PWA for official letter automation with Persian language support. Here's the complete application:

    1. HTML Structure (index.html)

    <!DOCTYPE html>
    <html lang="fa" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>سامانه خودکار تولید نامه‌های اداری</title>
        <link rel="manifest" href="manifest.json">
        <link rel="stylesheet" href="styles.css">
        <meta name="theme-color" content="#2196F3">
    </head>
    <body>
        <div id="app">
            <!-- Navigation -->
            <nav class="navbar">
                <div class="nav-container">
                    <h1>سامانه تولید نامه‌های اداری</h1>
                    <div class="nav-buttons">
                        <button id="projectsBtn" class="nav-btn active">پروژه‌ها</button>
                        <button id="templatesBtn" class="nav-btn">قالب‌ها</button>
                        <button id="lettersBtn" class="nav-btn">نامه‌ها</button>
                        <button id="settingsBtn" class="nav-btn">تنظیمات</button>
                    </div>
                </div>
            </nav>
    
            <!-- Projects Section -->
            <section id="projectsSection" class="section active">
                <div class="container">
                    <div class="section-header">
                        <h2>مدیریت پروژه‌ها</h2>
                        <button id="newProjectBtn" class="btn btn-primary">پروژه جدید</button>
                    </div>
                    <div id="projectsList" class="projects-grid"></div>
                </div>
            </section>
    
            <!-- Templates Section -->
            <section id="templatesSection" class="section">
                <div class="container">
                    <div class="section-header">
                        <h2>مدیریت قالب‌ها</h2>
                        <button id="newTemplateBtn" class="btn btn-primary">قالب جدید</button>
                    </div>
                    <div id="templatesList" class="templates-grid"></div>
                </div>
            </section>
    
            <!-- Letters Section -->
            <section id="lettersSection" class="section">
                <div class="container">
                    <div class="section-header">
                        <h2>ایجاد و مدیریت نامه‌ها</h2>
                        <button id="newLetterBtn" class="btn btn-primary">نامه جدید</button>
                    </div>
                    <div class="letter-workspace">
                        <div class="letter-controls">
                            <div class="control-group">
                                <label>انتخاب پروژه:</label>
                                <select id="projectSelect"></select>
                            </div>
                            <div class="control-group">
                                <label>انتخاب قالب:</label>
                                <select id="templateSelect"></select>
                            </div>
                            <div class="control-group">
                                <label>شماره نامه:</label>
                                <input type="text" id="letterNumber" readonly>
                            </div>
                        </div>
                        <div class="letter-editor">
                            <div class="editor-toolbar">
                                <button id="boldBtn" class="toolbar-btn">B</button>
                                <button id="italicBtn" class="toolbar-btn">I</button>
                                <button id="underlineBtn" class="toolbar-btn">U</button>
                                <select id="fontSelect">
                                    <option value="Vazir">وزیر</option>
                                    <option value="Yekan">یکان</option>
                                    <option value="Samim">صمیم</option>
                                </select>
                                <input type="number" id="fontSize" value="14" min="8" max="72">
                            </div>
                            <div class="letter-preview" id="letterPreview">
                                <div class="letter-header" id="letterHeader"></div>
                                <div class="letter-content" contenteditable="true" id="letterContent">
                                    <p>محتوای نامه را در اینجا وارد کنید...</p>
                                </div>
                                <div class="letter-footer" id="letterFooter"></div>
                                <div class="signature-area" id="signatureArea"></div>
                                <div class="stamp-area" id="stampArea"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
    
            <!-- Settings Section -->
            <section id="settingsSection" class="section">
                <div class="container">
                    <h2>تنظیمات</h2>
                    <div class="settings-grid">
                        <div class="setting-card">
                            <h3>فونت‌های سفارشی</h3>
                            <input type="file" id="fontUpload" accept=".ttf,.otf,.woff,.woff2" multiple>
                            <div id="customFontsList"></div>
                        </div>
                        <div class="setting-card">
                            <h3>پشتیبان‌گیری و بازیابی</h3>
                            <button id="exportDataBtn" class="btn btn-secondary">خروجی داده‌ها</button>
                            <input type="file" id="importDataInput" accept=".json" style="display: none;">
                            <button id="importDataBtn" class="btn btn-secondary">وارد کردن داده‌ها</button>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    
        <!-- Modals -->
        <div id="projectModal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <h3>پروژه جدید</h3>
                <form id="projectForm">
                    <div class="form-group">
                        <label>نام پروژه:</label>
                        <input type="text" id="projectName" required>
                    </div>
                    <div class="form-group">
                        <label>فرمت شماره نامه:</label>
                        <input type="text" id="numberFormat" placeholder="مثال: {YEAR}/{PROJECT}/{NUMBER}" required>
                    </div>
                    <div class="form-group">
                        <label>شماره شروع:</label>
                        <input type="number" id="startNumber" value="1" required>
                    </div>
                    <div class="form-group">
                        <label>توضیحات:</label>
                        <textarea id="projectDescription"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">ذخیره</button>
                </form>
            </div>
        </div>
    
        <div id="templateModal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <h3>قالب جدید</h3>
                <form id="templateForm">
                    <div class="form-group">
                        <label>نام قالب:</label>
                        <input type="text" id="templateName" required>
                    </div>
                    <div class="form-group">
                        <label>تصویر پس‌زمینه/هدر:</label>
                        <input type="file" id="backgroundImage" accept="image/*">
                        <canvas id="backgroundCanvas" style="border: 1px solid #ccc; max-width: 100%;"></canvas>
                    </div>
                    <div class="form-group">
                        <label>موقعیت امضا (X, Y):</label>
                        <input type="number" id="signatureX" placeholder="X"> 
                        <input type="number" id="signatureY" placeholder="Y">
                    </div>
                    <div class="form-group">
                        <label>موقعیت مهر (X, Y):</label>
                        <input type="number" id="stampX" placeholder="X">
                        <input type="number" id="stampY" placeholder="Y">
                    </div>
                    <button type="submit" class="btn btn-primary">ذخیره</button>
                </form>
            </div>
        </div>
    
        <script src="app.js"></script>
        <script>
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('sw.js');
            }
        </script>
    </body>
    </html>
    

    2. CSS Styles (styles.css)

    @import url('https://fonts.googleapis.com/css2?family=Vazir:wght@300;400;500;700&display=swap');
    
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        font-family: 'Vazir', sans-serif;
        direction: rtl;
        background-color: #f5f5f5;
        line-height: 1.6;
    }
    
    .navbar {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1rem 0;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    .nav-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 1rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .nav-buttons {
        display: flex;
        gap: 1rem;
    }
    
    .nav-btn {
        padding: 0.5rem 1rem;
        background: rgba(255,255,255,0.2);
        border: none;
        border-radius: 5px;
        color: white;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .nav-btn:hover, .nav-btn.active {
        background: rgba(255,255,255,0.3);
        transform: translateY(-2px);
    }
    
    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 2rem 1rem;
    }
    
    .section {
        display: none;
    }
    
    .section.active {
        display: block;
    }
    
    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 2rem;
    }
    
    .btn {
        padding: 0.75rem 1.5rem;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-family: inherit;
        font-size: 0.9rem;
        transition: all 0.3s;
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
    }
    
    .btn-secondary {
        background: #6c757d;
        color: white;
    }
    
    .projects-grid, .templates-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 1.5rem;
    }
    
    .project-card, .template-card {
        background: white;
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        transition: all 0.3s;
    }
    
    .project-card:hover, .template-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0,0,0,0.15);
    }
    
    .letter-workspace {
        background: white;
        border-radius: 10px;
        padding: 1.5rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    
    .letter-controls {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 1.5rem;
        padding-bottom: 1.5rem;
        border-bottom: 1px solid #eee;
    }
    
    .control-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .control-group label {
        font-weight: 500;
        color: #333;
    }
    
    .control-group input, .control-group select {
        padding: 0.5rem;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-family: inherit;
    }
    
    .editor-toolbar {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 1rem;
        padding: 0.5rem;
        background: #f8f9fa;
        border-radius: 5px;
    }
    
    .toolbar-btn {
        padding: 0.5rem;
        background: white;
        border: 1px solid #ddd;
        border-radius: 3px;
        cursor: pointer;
        min-width: 35px;
    }
    
    .toolbar-btn:hover {
        background: #e9ecef;
    }
    
    .letter-preview {
        position: relative;
        min-height: 800px;
        background: white;
        border: 1px solid #ddd;
        margin: 1rem 0;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center top;
    }
    
    .letter-header, .letter-footer {
        min-height: 100px;
        background-size: contain;
        background-repeat: no-repeat;
        background-position: center;
    }
    
    .letter-content {
        padding: 2rem;
        min-height: 400px;
        font-size: 14px;
        line-height: 2;
        text-align: justify;
    }
    
    .letter-content:focus {
        outline: 2px solid #667eea;
        outline-offset: -2px;
    }
    
    .signature-area, .stamp-area {
        position: absolute;
        width: 100px;
        height: 50px;
        border: 2px dashed #ccc;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.8rem;
        color: #666;
        cursor: move;
    }
    
    .signature-area {
        bottom: 100px;
        left: 50px;
    }
    
    .stamp-area {
        bottom: 50px;
        left: 200px;
    }
    
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }
    
    .modal-content {
        background-color: white;
        margin: 5% auto;
        padding: 2rem;
        border-radius: 10px;
        width: 90%;
        max-width: 600px;
        max-height: 90vh;
        overflow-y: auto;
    }
    
    .close {
        color: #aaa;
        float: left;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
    }
    
    .close:hover {
        color: black;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
    }
    
    .form-group input, .form-group textarea, .form-group select {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-family: inherit;
        font-size: 0.9rem;
    }
    
    .form-group textarea {
        min-height: 100px;
        resize: vertical;
    }
    
    .settings-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 1.5rem;
    }
    
    .setting-card {
        background: white;
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    
    #backgroundCanvas {
        max-width: 100%;
        margin-top: 1rem;
        cursor: crosshair;
    }
    
    /* Persian fonts */
    @font-face {
        font-family: 'Yekan';
        src: url('fonts/Yekan.woff2') format('woff2');
    }
    
    @font-face {
        font-family: 'Samim';
        src: url('fonts/Samim.woff2') format('woff2');
    }
    
    /* Responsive design */
    @media (max-width: 768px) {
        .nav-container {
            flex-direction: column;
            gap: 1rem;
        }
    
        .nav-buttons {
            flex-wrap: wrap;
            justify-content: center;
        }
    
        .section-header {
            flex-direction: column;
            gap: 1rem;
            text-align: center;
        }
    
        .letter-controls {
            grid-template-columns: 1fr;
        }
    
        .projects-grid, .templates-grid {
            grid-template-columns: 1fr;
        }
    }
    
    /* Print styles */
    @media print {
        .navbar, .letter-controls, .editor-toolbar {
            display: none !important;
        }
        
        .letter-preview {
            border: none !important;
            box-shadow: none !important;
        }
        
        .signature-area, .stamp-area {
            border: none !important;
            background: transparent !important;
        }
    }
    

    3. JavaScript Application (app.js)

    class LetterAutomationApp {
        constructor() {
            this.projects = JSON.parse(localStorage.getItem('projects')) || [];
            this.templates = JSON.parse(localStorage.getItem('templates')) || [];
            this.letters = JSON.parse(localStorage.getItem('letters')) || [];
            this.customFonts = JSON.parse(localStorage.getItem('customFonts')) || [];
            this.currentProject = null;
            this.currentTemplate = null;
            
            this.init();
        }
    
        init() {
            this.setupNavigation();
            this.setupEventListeners();
            this.loadProjects();
            this.loadTemplates();
            this.loadCustomFonts();
            this.loadProjectSelect();
            this.loadTemplateSelect();
        }
    
        setupNavigation() {
            const navButtons = document.querySelectorAll('.nav-btn');
            const sections = document.querySelectorAll('.section');
    
            navButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    const targetSection = btn.id.replace('Btn', 'Section');
                    
                    navButtons.forEach(b => b.classList.remove('active'));
                    sections.forEach(s => s.classList.remove('active'));
                    
                    btn.classList.add('active');
                    document.getElementById(targetSection).classList.add('active');
                });
            });
        }
    
        setupEventListeners() {
            // Project management
            document.getElementById('newProjectBtn').addEventListener('click', () => {
                this.openProjectModal();
            });
    
            document.getElementById('projectForm').addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveProject();
            });
    
            // Template management
            document.getElementById('newTemplateBtn').addEventListener('click', () => {
                this.openTemplateModal();
            });
    
            document.getElementById('templateForm').addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveTemplate();
            });
    
            // Letter management
            document.getElementById('projectSelect').addEventListener('change', (e) => {
                this.currentProject = this.projects.find(p => p.id === e.target.value);
                this.updateLetterNumber();
            });
    
            document.getElementById('templateSelect').addEventListener('change', (e) => {
                this.currentTemplate = this.templates.find(t => t.id === e.target.value);
                this.applyTemplate();
            });
    
            // Editor functionality
            document.getElementById('boldBtn').addEventListener('click', () => {
                document.execCommand('bold');
            });
    
            document.getElementById('italicBtn').addEventListener('click', () => {
                document.execCommand('italic');
            });
    
            document.getElementById('underlineBtn').addEventListener('click', () => {
                document.execCommand('underline');
            });
    
            document.getElementById('fontSelect').addEventListener('change', (e) => {
                document.execCommand('fontName', false, e.target.value);
            });
    
            document.getElementById('fontSize').addEventListener('change', (e) => {
                document.execCommand('fontSize', false, '7');
                const selection = window.getSelection();
                if (selection.rangeCount > 0) {
                    const range = selection.getRangeAt(0);
                    const span = document.createElement('span');
                    span.style.fontSize = e.target.value + 'px';
                    range.surroundContents(span);
                }
            });
    
            // Background canvas setup
            document.getElementById('backgroundImage').addEventListener('change', (e) => {
                this.loadBackgroundImage(e.target.files[0]);
            });
    
            // Font upload
            document.getElementById('fontUpload').addEventListener('change', (e) => {
                this.uploadCustomFonts(e.target.files);
            });
    
            // Data import/export
            document.getElementById('exportDataBtn').addEventListener('click', () => {
                this.exportData();
            });
    
            document.getElementById('importDataBtn').addEventListener('click', () => {
                document.getElementById('importDataInput').click();
            });
    
            document.getElementById('importDataInput').addEventListener('change', (e) => {
                this.importData(e.target.files[0]);
            });
    
            // Modal controls
            document.querySelectorAll('.close').forEach(closeBtn => {
                closeBtn.addEventListener('click', () => {
                    closeBtn.closest('.modal').style.display = 'none';
                });
            });
    
            window.addEventListener('click', (e) => {
                if (e.target.classList.contains('modal')) {
                    e.target.style.display = 'none';
                }
            });
    
            // Drag functionality for signature and stamp areas
            this.makeDraggable(document.getElementById('signatureArea'));
            this.makeDraggable(document.getElementById('stampArea'));
        }
    
        // Project Management
        openProjectModal(project = null) {
            const modal = document.getElementById('projectModal');
            const form = document.getElementById('projectForm');
            
            if (project) {
                document.getElementById('projectName').value = project.name;
                document.getElementById('numberFormat').value = project.numberFormat;
                document.getElementById('startNumber').value = project.startNumber;
                document.getElementById('projectDescription').value = project.description || '';
                form.dataset.projectId = project.id;
            } else {
                form.reset();
                delete form.dataset.projectId;
            }
            
            modal.style.display = 'block';
        }
    
        saveProject() {
            const form = document.getElementById('projectForm');
            const projectData = {
                id: form.dataset.projectId || this.generateId(),
                name: document.getElementById('projectName').value,
                numberFormat: document.getElementById('numberFormat').value,
                startNumber: parseInt(document.getElementById('startNumber').value),
                currentNumber: parseInt(document.getElementById('startNumber').value),
                description: document.getElementById('projectDescription').value,
                createdAt: new Date().toISOString()
            };
    
            if (form.dataset.projectId) {
                const index = this.projects.findIndex(p => p.id === form.dataset.projectId);
                this.projects[index] = { ...this.projects[index], ...projectData };
            } else {
                this.projects.push(projectData);
            }
    
            this.saveToStorage('projects', this.projects);
            this.loadProjects();
            this.loadProjectSelect();
            document.getElementById('projectModal').style.display = 'none';
        }
    
        loadProjects() {
            const container = document.getElementById('projectsList');
            container.innerHTML = '';
    
            this.projects.forEach(project => {
                const projectCard = document.createElement('div');
                projectCard.className = 'project-card';
                projectCard.innerHTML = `
                    <h3>${project.name}</h3>
                    <p><strong>فرمت شماره:</strong> ${project.numberFormat}</p>
                    <p><strong>شماره فعلی:</strong> ${project.currentNumber}</p>
                    <p><strong>توضیحات:</strong> ${project.description || 'ندارد'}</p>
                    <div style="margin-top: 1rem;">
                        <button onclick="app.openProjectModal(app.projects.find(p => p.id === '${project.id}'))" class="btn btn-secondary">ویرایش</button>
                        <button onclick="app.deleteProject('${project.id}')" class="btn" style="background: #dc3545; color: white;">حذف</button>
                    </div>
                `;
                container.appendChild(projectCard);
            });
        }
    
        deleteProject(projectId) {
            if (confirm('آیا از حذف این پروژه اطمینان دارید؟')) {
                this.projects = this.projects.filter(p => p.id !== projectId);
                this.saveToStorage('projects', this.projects);
                this.loadProjects();
                this.loadProjectSelect();
            }
        }
    
        loadProjectSelect() {
            const select = document.getElementById('projectSelect');
            select.innerHTML = '<option value="">انتخاب پروژه</option>';
            
            this.projects.forEach(project => {
                const option = document.createElement('option');
                option.value = project.id;
                option.textContent = project.name;
                select.appendChild(option);
            });
        }
    
        // Template Management
        openTemplateModal(template = null) {
            const modal = document.getElementById('templateModal');
            const form = document.getElementById('templateForm');
            
            if (template) {
                document.getElementById('templateName').value = template.name;
                document.getElementById('signatureX').value = template.signatureX || 50;
                document.getElementById('signatureY').value = template.signatureY || 100;
                document.getElementById('stampX').value = template.stampX || 200;
                document.getElementById('stampY').value = template.stampY || 50;
                form.dataset.templateId = template.id;
                
                if (template.backgroundImage) {
                    this.displayBackgroundImage(template.backgroundImage);
                }
            } else {
                form.reset();
                delete form.dataset.templateId;
                this.clearBackgroundCanvas();
            }
            
            modal.style.display = 'block';
        }
    
        saveTemplate() {
            const form = document.getElementById('templateForm');
            const canvas = document.getElementById('backgroundCanvas');
            const backgroundImage = canvas.toDataURL();
            
            const templateData = {
                id: form.dataset.templateId || this.generateId(),
                name: document.getElementById('templateName').value,
                backgroundImage: backgroundImage,
                signatureX: parseInt(document.getElementById('signatureX').value) || 50,
                signatureY: parseInt(document.getElementById('signatureY').value) || 100,
                stampX: parseInt(document.getElementById('stampX').value) || 200,
                stampY: parseInt(document.getElementById('stampY').value) || 50,
                createdAt: new Date().toISOString()
            };
    
            if (form.dataset.templateId) {
                const index = this.templates.findIndex(t => t.id === form.dataset.templateId);
                this.templates[index] = { ...this.templates[index], ...templateData };
            } else {
                this.templates.push(templateData);
            }
    
            this.saveToStorage('templates', this.templates);
            this.loadTemplates();
            this.loadTemplateSelect();
            document.getElementById('templateModal').style.display = 'none';
        }
    
        loadTemplates() {
            const container = document.getElementById('templatesList');
            container.innerHTML = '';
    
            this.templates.forEach(template => {
                const templateCard = document.createElement('div');
                templateCard.className = 'template-card';
                templateCard.innerHTML = `
                    <h3>${template.name}</h3>
                    <div style="margin: 1rem 0;">
                        <img src="${template.backgroundImage}" style="max-width: 100%; height: 150px; object-fit: contain;">
                    </div>
                    <div style="margin-top: 1rem;">
                        <button onclick="app.openTemplateModal(app.templates.find(t => t.id === '${template.id}'))" class="btn btn-secondary">ویرایش</button>
                        <button onclick="app.deleteTemplate('${template.id}')" class="btn" style="background: #dc3545; color: white;">حذف</button>
                    </div>
                `;
                container.appendChild(templateCard);
            });
        }
    
        deleteTemplate(templateId) {
            if (confirm('آیا از حذف این قالب اطمینان دارید؟')) {
                this.templates = this.templates.filter(t => t.id !== templateId);
                this.saveToStorage('templates', this.templates);
                this.loadTemplates();
                this.loadTemplateSelect();
            }
        }
    
        loadTemplateSelect() {
            const select = document.getElementById('templateSelect');
            select.innerHTML = '<option value="">انتخاب قالب</option>';
            
            this.templates.forEach(template => {
                const option = document.createElement('option');
                option.value = template.id;
                option.textContent = template.name;
                select.appendChild(option);
            });
        }
    
        // Background Image Handling
        loadBackgroundImage(file) {
            if (!file) return;
    
            const reader = new FileReader();
            reader.onload = (e) => {
                this.displayBackgroundImage(e.target.result);
            };
            reader.readAsDataURL(file);
        }
    
        displayBackgroundImage(imageSrc) {
            const canvas = document.getElementById('backgroundCanvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();
            
            img.onload = () => {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
                
                // Add click event for positioning
                canvas.onclick = (e) => {
                    const rect = canvas.getBoundingClientRect();
                    const x = (e.clientX - rect.left) * (canvas.width / rect.width);
                    const y = (e.clientY - rect.top) * (canvas.height / rect.height);
                    
                    if (e.shiftKey) {
                        document.getElementById('stampX').value = Math.round(x);
                        document.getElementById('stampY').value = Math.round(y);
                    } else {
                        document.getElementById('signatureX').value = Math.round(x);
                        document.getElementById('signatureY').value = Math.round(y);
                    }
                };
            };
            
            img.src = imageSrc;
        }
    
        clearBackgroundCanvas() {
            const canvas = document.getElementById('backgroundCanvas');
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
    
        // Letter Management
        updateLetterNumber() {
            if (!this.currentProject) return;
    
            const letterNumber = this.generateLetterNumber(this.currentProject);
            document.getElementById('letterNumber').value = letterNumber;
        }
    
        generateLetterNumber(project) {
            const year = new Date().getFullYear();
            const month = new Date().getMonth() + 1;
            const day = new Date().getDate();
            
            return project.numberFormat
                .replace('{YEAR}', year)
                .replace('{MONTH}', month.toString().padStart(2, '0'))
                .replace('{DAY}', day.toString().padStart(2, '0'))
                .replace('{PROJECT}', project.name)
                .replace('{NUMBER}', project.currentNumber.toString().padStart(3, '0'));
        }
    
        applyTemplate() {
            if (!this.currentTemplate) return;
    
            const letterPreview = document.getElementById('letterPreview');
            const signatureArea = document.getElementById('signatureArea');
            const stampArea = document.getElementById('stampArea');
    
            // Apply background image
            letterPreview.style.backgroundImage = `url(${this.currentTemplate.backgroundImage})`;
            
            // Position signature and stamp areas
            signatureArea.style.left = this.currentTemplate.signatureX + 'px';
            signatureArea.style.bottom = this.currentTemplate.signatureY + 'px';
            stampArea.style.left = this.currentTemplate.stampX + 'px';
            stampArea.style.bottom = this.currentTemplate.stampY + 'px';
        }
    
        // Custom Fonts
        uploadCustomFonts(files) {
            Array.from(files).forEach(file => {
                if (file.type.includes('font') || file.name.endsWith('.ttf') || file.name.endsWith('.otf') || file.name.endsWith('.woff') || file.name.endsWith('.woff2')) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const fontData = {
                            id: this.generateId(),
                            name: file.name.split('.')[0],
                            data: e.target.result,
                            type: file.type
                        };
                        
                        this.customFonts.push(fontData);
                        this.saveToStorage('customFonts', this.customFonts);
                        this.loadCustomFonts();
                        this.addFontToSystem(fontData);
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
    
        loadCustomFonts() {
            const container = document.getElementById('customFontsList');
            container.innerHTML = '';
            
            this.customFonts.forEach(font => {
                this.addFontToSystem(font);
                
                const fontItem = document.createElement('div');
                fontItem.innerHTML = `
                    <span>${font.name}</span>
                    <button onclick="app.deleteCustomFont('${font.id}')" style="margin-right: 10px; background: #dc3545; color: white; border: none; padding: 5px 10px; border-radius: 3px;">حذف</button>
                `;
                container.appendChild(fontItem);
            });
        }
    
        addFontToSystem(font) {
            const style = document.createElement('style');
            style.textContent = `
                @font-face {
                    font-family: '${font.name}';
                    src: url('${font.data}');
                }
            `;
            document.head.appendChild(style);
            
            // Add to font select
            const fontSelect = document.getElementById('fontSelect');
            if (!Array.from(fontSelect.options).find(option => option.value === font.name)) {
                const option = document.createElement('option');
                option.value = font.name;
                option.textContent = font.name;
                fontSelect.appendChild(option);
            }
        }
    
        deleteCustomFont(fontId) {
            this.customFonts = this.customFonts.filter(f => f.id !== fontId);
            this.saveToStorage('customFonts', this.customFonts);
            this.loadCustomFonts();
        }
    
        // Drag functionality
        makeDraggable(element) {
            let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            
            element.onmousedown = dragMouseDown;
            
            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                document.onmousemove = elementDrag;
            }
            
            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                element.style.top = (element.offsetTop - pos2) + "px";
                element.style.left = (element.offsetLeft - pos1) + "px";
            }
            
            function closeDragElement() {
                document.onmouseup = null;
                document.onmousemove = null;
            }
        }
    
        // Data Management
        exportData() {
            const data = {
                projects: this.projects,
                templates: this.templates,
                letters: this.letters,
                customFonts: this.customFonts,
                exportDate: new Date().toISOString()
            };
            
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `letter_automation_backup_${new Date().toISOString().split('T')[0]}.json`;
            a.click();
            URL.revokeObjectURL(url);
        }
    
        importData(file) {
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    
                    if (confirm('آیا از وارد کردن داده‌ها اطمینان دارید؟ این عمل داده‌های فعلی را جایگزین خواهد کرد.')) {
                        this.projects = data.projects || [];
                        this.templates = data.templates || [];
                        this.letters = data.letters || [];
                        this.customFonts = data.customFonts || [];
                        
                        this.saveToStorage('projects', this.projects);
                        this.saveToStorage('templates', this.templates);
                        this.saveToStorage('letters', this.letters);
                        this.saveToStorage('customFonts', this.customFonts);
                        
                        location.reload();
                    }
                } catch (error) {
                    alert('خطا در خواندن فایل: ' + error.message);
                }
            };
            reader.readAsText(file);
        }
    
        // Utility functions
        generateId() {
            return Date.now().toString(36) + Math.random().toString(36).substr(2);
        }
    
        saveToStorage(key, data) {
            localStorage.setItem(key, JSON.stringify(data));
        }
    }
    
    // Initialize the app
    const app = new LetterAutomationApp();
    

    4. Service Worker (sw.js)

    const CACHE_NAME = 'letter-automation-v1';
    const urlsToCache = [
        '/',
        '/index.html',
        '/styles.css',
        '/app.js',
        '/manifest.json',
        'https://fonts.googleapis.com/css2?family=Vazir:wght@300;400;500;700&display=swap'
    ];
    
    self.addEventListener('install', event => {
        event.waitUntil(
            caches.open(CACHE_NAME)
                .then(cache => cache.addAll(urlsToCache))
        );
    });
    
    self.addEventListener('fetch', event => {
        event.respondWith(
            caches.match(event.request)
                .then(response => {
                    if (response) {
                        return response;
                    }
                    return fetch(event.request);
                })
        );
    });
    

    5. PWA Manifest (manifest.json)

    {
        "name": "سامانه خودکار تولید نامه‌های اداری",
        "short_name": "نامه‌ساز",
        "description": "سامانه جامع برای تولید خودکار نامه‌های اداری با پشتیبانی از زبان فارسی",
        "start_url": "/",
        "display": "standalone",
        "background_color": "#f5f5f5",
        "theme_color": "#2196F3",
        "orientation": "portrait",
        "icons": [
            {
                "src": "icon-192.png",
                "sizes": "192x192",
                "type": "image/png"
            },
            {
                "src": "icon-512.png",
                "sizes": "512x512",
                "type": "image/png"
            }
        ]
    }
    

    Key Features Implemented:

    1. Persian Language Support: Complete RTL support with Persian fonts
    2. Project Management: Create projects with custom letter numbering formats
    3. Template System: Upload backgrounds, position signatures and stamps
    4. Custom Fonts: Upload and use custom Persian fonts
    5. Letter Editor: Rich text editor with Persian support
    6. Progressive Web App: Offline functionality with service worker
    7. Data Management: Export/import functionality for backup
    8. Responsive Design: Works on desktop and mobile devices

    Installation:

    1. Create a new directory for your project
    2. Save each file with its respective name
    3. Add Persian font files to a fonts directory
    4. Create icon files (icon-192.png, icon-512.png)
    5. Serve the files using a local server (e.g., python -m http.server)

    The application provides a complete solution for automated official letter creation with Persian language support, custom fonts, templates, and project management capabilities.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt