Untitled
unknown
plain_text
2 months ago
13 kB
4
Indexable
//upload_file.js // Danh sách các user được quyền const ALLOWED_USERS = ['sontg', 'user2', 'user3']; // Hàm kiểm tra quyền function isUserAllowed(userName) { return ALLOWED_USERS.includes(userName); } async function upload_document() { // const userName = localStorage.getItem('user_name'); // if (!isUserAllowed(userName)) { // alert('Bạn không có quyền thực hiện thao tác này'); // return; // } try { updateNewSession() setViewState('file_upload'); // Lưu trạng thái // Tạo giao diện danh sách file const chatSection = document.querySelector('.chat-section'); chatSection.innerHTML = ` <div class="file-manager"> <div class="file-header"> <h2>Danh sách tài liệu quy trình</h2> <div class="upload-section"> <input type="file" id="fileInput" accept=".pdf,.docx" style="display: none"> <button onclick="document.getElementById('fileInput').click()" class="upload-btn">Chọn file</button> <button onclick="processFiles()" class="process-btn">Xử lý file</button> <button onclick="returnToChat()" class="return-btn">Quay lại chat</button> </div> </div> <div class="file-list" id="fileList"> <div class="loading">Đang tải danh sách file...</div> </div> </div> `; // Thêm event listener cho input file document.getElementById('fileInput').addEventListener('change', handleFileUpload); // Lấy và hiển thị danh sách file ban đầu const files = await FileManager.getFileList(); updateFileList(files); } catch (error) { console.error('Error:', error); const fileList = document.getElementById('fileList'); if (fileList) { fileList.innerHTML = '<div class="error">Không thể tải danh sách file</div>'; } } } async function handleFileUpload(e) { const userName = localStorage.getItem('user_name'); if (!isUserAllowed(userName)) { alert('Bạn không có quyền thực hiện thao tác này'); return; } const file = e.target.files[0]; if (file) { const fileList = document.getElementById('fileList'); fileList.innerHTML = '<div class="loading">Đang tải file lên...</div>'; try { const result = await FileManager.uploadFile(file); if (result.status === 'success') { const files = await FileManager.getFileList(); updateFileList(files); } else { throw new Error(result.message); } } catch (error) { console.error('Error:', error); fileList.innerHTML = '<div class="error">Không thể tải file lên</div>'; } } } function updateFileList(files) { const fileList = document.getElementById('fileList'); if (files && files.length > 0) { fileList.innerHTML = files.map(file => ` <div class="file-item"> <span class="file-name">${file}</span> <div class="file-menu"> <button class="more-actions">⋮</button> <div class="file-actions"> <button class="action-btn" onclick="downloadFile('${file}')"> <i class="fas fa-download"></i> Tải xuống </button> <button class="action-btn" onclick="renameFile('${file}')"> <i class="fas fa-edit"></i> Đổi tên </button> <button class="action-btn" onclick="deleteFile('${file}')"> <i class="fas fa-trash"></i> Xóa </button> </div> </div> </div> `).join(''); setupFileActions(); } else { fileList.innerHTML = '<div class="no-files">Không có file nào</div>'; } } function setupFileActions() { // Thêm event listener cho các nút more-actions document.querySelectorAll('.more-actions').forEach(button => { button.addEventListener('click', function(e) { e.stopPropagation(); // Đóng tất cả các menu đang mở document.querySelectorAll('.file-actions').forEach(menu => { menu.classList.remove('show'); }); // Mở menu của nút được click const actions = this.nextElementSibling; actions.classList.toggle('show'); }); }); // Đóng menu khi click ra ngoài document.addEventListener('click', function(e) { if (!e.target.matches('.more-actions')) { document.querySelectorAll('.file-actions').forEach(menu => { menu.classList.remove('show'); }); } }); } async function downloadFile(fileName) { try { const response = await FileManager.downloadFile(fileName); if (response.status === 'success') { console.log('File downloaded successfully'); } else { throw new Error(response.message || 'Unknown error occurred'); } } catch (error) { console.error('Error downloading file:', error); alert('Không thể tải file xuống'); } } async function renameFile(fileName) { const userName = localStorage.getItem('user_name'); if (!isUserAllowed(userName)) { alert('Bạn không có quyền thực hiện thao tác này'); return; } const newName = prompt('Nhập tên mới cho file:', fileName); if (newName && newName !== fileName) { try { const response = await FileManager.renameFile(fileName, newName); if (response.status === 'success') { const files = await FileManager.getFileList(); updateFileList(files); } else { throw new Error(response.message); } } catch (error) { console.error('Error renaming file:', error); alert('Không thể đổi tên file'); } } } async function deleteFile(fileName) { const userName = localStorage.getItem('user_name'); if (!isUserAllowed(userName)) { alert('Bạn không có quyền thực hiện thao tác này'); return; } if (confirm(`Bạn có chắc muốn xóa file "${fileName}"?`)) { try { const response = await FileManager.deleteFile(fileName); if (response.status === 'success') { const files = await FileManager.getFileList(); updateFileList(files); } else { throw new Error(response.message); } } catch (error) { console.error('Error deleting file:', error); alert('Không thể xóa file'); } } } async function processFiles() { const userName = localStorage.getItem('user_name'); if (!isUserAllowed(userName)) { alert('Bạn không có quyền thực hiện thao tác này'); return; } try { const response = await FileManager.processFiles(); if (response.status === 'success') { alert('Xử lý file thành công'); } else { throw new Error(response.message); } } catch (error) { console.error('Error processing files:', error); alert('Không thể xử lý file'); } } function returnToChat() { setViewState('chat'); // Lưu trạng thái const chatSection = document.querySelector('.chat-section'); chatSection.innerHTML = ''; // Xóa nội dung cũ chatSection.innerHTML = ` <div class="chat-container"> <div class="chat-header"> <h2>Trợ lý giải đáp thông tin quy trình P.TCKT Tổng công ty CP Công trình Viettel</h2> </div> <div class="chat-messages" id="chatMessages"></div> <div class="chat-input"> <input type="text" id="userInput" placeholder="Nhập câu hỏi của bạn..."/> <button onclick="sendMessage()" id="sendButton">Gửi</button> </div> </div> `; loadChatHistory(); } // upload_file.js class FileManager { static async _fetchData(url, options = {}) { try { const response = await fetch(url, options); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.detail || `HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error(`Error in ${options.method || 'GET'} request to ${url}:`, error); throw error; } } static async getFileList() { return this._fetchData(`${BASE_URL}/get_file_list`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); } static async uploadFile(file) { const formData = new FormData(); formData.append('file', file); // Lấy các thông tin từ localStorage const userName = localStorage.getItem('user_name'); const employeeId = localStorage.getItem('employee_id'); const time_stamp = new Date().toISOString(); // Lấy thời gian hiện tại dưới dạng ISO string // Thêm các thông tin vào formData formData.append('file_name', file.name); // Tên file formData.append('userName', userName); // Tên người dùng formData.append('employeeId', employeeId); // ID nhân viên formData.append('time_stamp', time_stamp); // Thời gian upload return this._fetchData(`${BASE_URL}/upload_file`, { method: 'POST', body: formData, }); } static async downloadFile(fileName) { try { const response = await fetch(`${BASE_URL}/files/download/${fileName}`, { method: 'GET', }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const blob = await response.blob(); if (!blob || blob.size === 0) { throw new Error('Received an empty file.'); } const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove(); return { status: 'success' }; } catch (error) { console.error('Download error:', error); return { status: 'error', message: error.message }; } } static async renameFile(oldName, newName) { try { const formData = new FormData(); formData.append('old_name', oldName); formData.append('new_name', newName); const response = await fetch(`${BASE_URL}/files/rename`, { method: 'POST', body: formData }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.detail || `HTTP error! status: ${response.status}`); } const result = await response.json(); return { status: 'success', data: result }; } catch (error) { console.error('Rename error:', error); return { status: 'error', message: error.message }; } } static async deleteFile(fileName) { try { const response = await fetch(`${BASE_URL}/files/delete/${fileName}`, { method: 'DELETE' }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.detail || `HTTP error! status: ${response.status}`); } const result = await response.json(); return { status: 'success', data: result }; } catch (error) { console.error('Delete error:', error); return { status: 'error', message: error.message }; } } async processFiles() { return this._fetchData(`${BASE_URL}/files/process`, { method: 'POST', }); } } // Export class FileManager if (typeof module !== 'undefined' && module.exports) { module.exports = FileManager; }
Editor is loading...
Leave a Comment