File size: 7,905 Bytes
bbfde3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# Frontend Integration Guide - Session-Based Batch Processing

## πŸš€ NEW ENDPOINTS AVAILABLE

### 1. **Session Management** - `/api/session`
**Purpose**: Initialize and maintain user sessions for temporary file storage

```javascript

// Initialize session when user opens the app

POST /api/session

Response: { sessionId: "1762145344331-h6evl2etm", success: true }



// Keep session alive (call every 5 minutes while user is active)

POST /api/session

Headers: { "X-Session-ID": "session-id-here" }

Response: { success: true, message: "Session refreshed" }



// Get session info and existing batches

GET /api/session?sessionId=session-id-here

Response: { 

  sessionId: "...", 

  files: [...], 

  batches: [...],

  expiresIn: "1 hour from last activity"

}

```

### 2. **Batch Upload** - `/api/batch-upload`
**Purpose**: Upload and process multiple DOCX files at once (up to 10 files)

```javascript

// Upload multiple files

POST /api/batch-upload

Headers: { "X-Session-ID": "session-id-here" }

Body: FormData with multiple files



Response: {

  sessionId: "session-id-here",

  batchId: 1762145344343,

  summary: {

    totalFiles: 5,

    successful: 4,

    failed: 1

  },

  results: [

    {

      fileIndex: 1,

      filename: "document1.docx",

      success: true,

      reportId: "report-123",

      summary: { flagged: 2, fixed: 1 },

      details: { ... }

    },

    // ... more files

  ],

  expiresIn: "1 hour"

}

```

### 3. **Batch Download** - `/api/batch-download`
**Purpose**: Download all remediated files as a ZIP

```javascript

// Download remediated files

GET /api/batch-download?batchId=1762145344343&sessionId=session-id-here

Response: ZIP file containing all remediated documents

```

---

## πŸ“‹ FRONTEND IMPLEMENTATION CHECKLIST

### Step 1: **Session Initialization** (Required)
```javascript

class AccessibilityChecker {

  constructor() {

    this.sessionId = null;

    this.heartbeatInterval = null;

  }



  async initializeSession() {

    try {

      const response = await fetch('/api/session', {

        method: 'POST',

        headers: { 'Content-Type': 'application/json' }

      });

      const data = await response.json();

      this.sessionId = data.sessionId;

      

      // Start heartbeat to keep session alive

      this.startHeartbeat();

      

      return this.sessionId;

    } catch (error) {

      console.error('Session initialization failed:', error);

    }

  }



  startHeartbeat() {

    // Send heartbeat every 5 minutes while user is active

    this.heartbeatInterval = setInterval(async () => {

      if (this.sessionId) {

        try {

          await fetch('/api/session', {

            method: 'POST',

            headers: {

              'Content-Type': 'application/json',

              'X-Session-ID': this.sessionId

            }

          });

        } catch (error) {

          console.warn('Heartbeat failed:', error);

        }

      }

    }, 5 * 60 * 1000); // 5 minutes

  }



  cleanup() {

    if (this.heartbeatInterval) {

      clearInterval(this.heartbeatInterval);

    }

    // Note: Server will auto-cleanup files after 1 hour

  }

}



// Initialize when app loads

const checker = new AccessibilityChecker();

checker.initializeSession();



// Cleanup when user leaves

window.addEventListener('beforeunload', () => checker.cleanup());

```

### Step 2: **Multi-File Upload UI** (Recommended)
```javascript

async function uploadMultipleFiles(files) {

  if (!checker.sessionId) {

    throw new Error('Session not initialized');

  }



  const formData = new FormData();

  files.forEach((file, index) => {

    formData.append(`file${index}`, file);

  });



  const response = await fetch('/api/batch-upload', {

    method: 'POST',

    headers: {

      'X-Session-ID': checker.sessionId

    },

    body: formData

  });



  if (!response.ok) {

    throw new Error(`Upload failed: ${response.statusText}`);

  }



  return await response.json();

}



// Usage example:

document.getElementById('fileInput').addEventListener('change', async (e) => {

  const files = Array.from(e.target.files);

  try {

    const result = await uploadMultipleFiles(files);

    console.log(`Processed ${result.summary.totalFiles} files`);

    console.log(`Batch ID: ${result.batchId}`);

    

    // Show results to user

    displayBatchResults(result);

  } catch (error) {

    console.error('Upload error:', error);

  }

});

```

### Step 3: **Download Remediated Files** (Required)
```javascript

function downloadBatch(batchId) {

  if (!checker.sessionId) {

    alert('Session expired. Please refresh the page.');

    return;

  }



  const downloadUrl = `/api/batch-download?batchId=${batchId}&sessionId=${checker.sessionId}`;

  

  // Create temporary download link

  const link = document.createElement('a');

  link.href = downloadUrl;

  link.download = `batch-${batchId}-remediated.zip`;

  document.body.appendChild(link);

  link.click();

  document.body.removeChild(link);

}

```

---

## πŸ”„ MIGRATION FROM EXISTING ENDPOINTS

### If you're currently using single-file endpoints:

**Old way:**
```javascript

// Single file upload

POST /api/upload-document

POST /api/download-document

```

**New way (backward compatible):**
```javascript

// Keep using single file endpoints for 1 file

// OR use batch endpoints for 1+ files



// For multiple files:

POST /api/batch-upload (new)

GET /api/batch-download (new)

```

### **Integration Options:**

1. **Quick Integration** (minimal changes):
   - Add session initialization on app start
   - Keep existing single-file flow
   - Add optional multi-file upload as new feature

2. **Full Integration** (recommended):
   - Replace single-file with batch endpoints
   - Add drag-and-drop for multiple files
   - Show batch progress and results

---

## 🎯 UI/UX RECOMMENDATIONS

### **File Upload Area:**
```html

<!-- Support both single and multiple files -->

<input type="file" multiple accept=".docx" id="fileInput">



<!-- Or drag-and-drop area -->

<div id="dropArea">

  <p>Drop up to 10 DOCX files here, or click to select</p>

  <button>Select Files</button>

</div>

```

### **Progress Display:**
```javascript

// Show batch processing progress

function displayBatchResults(result) {

  const container = document.getElementById('results');

  

  container.innerHTML = `

    <h3>Batch Processing Complete</h3>

    <p>Processed: ${result.summary.totalFiles} files</p>

    <p>Successful: ${result.summary.successful}</p>

    <p>Failed: ${result.summary.failed}</p>

    

    <button onclick="downloadBatch('${result.batchId}')">

      Download All Remediated Files

    </button>

    

    <div class="file-list">

      ${result.results.map(file => `

        <div class="file-result ${file.success ? 'success' : 'error'}">

          <strong>${file.filename}</strong>

          ${file.success ? 

            `<span>βœ“ ${file.summary.fixed} issues fixed</span>` :

            `<span>βœ— ${file.error}</span>`

          }

        </div>

      `).join('')}

    </div>

  `;

}

```

---

## 🚨 IMPORTANT NOTES

1. **Session Required**: All new endpoints require a valid session ID
2. **Auto-Cleanup**: Files expire after 1 hour of inactivity 
3. **No Permanent Storage**: Files are NOT saved permanently on the server
4. **Batch Limit**: Maximum 10 files per batch upload
5. **File Size**: Standard DOCX file size limits apply per file

---

## πŸ“ž IMPLEMENTATION SUPPORT

**Ready-to-use example**: See `docs/batch-processing.html` for complete working implementation

**Test endpoints**: Use the existing test files in `tests/fixtures/` for testing

**Questions?** The backend is ready - just implement the session management and you're good to go! πŸš€