Advertisement
niammuddin

edit bonding vyos

Mar 24th, 2024 (edited)
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.   // edit Bonding
  2.   function editBonding(data) {
  3.     let modalContent = '<div class="mt-3 mb-10"><div class="dataTables_processing" role="status"><div><div></div><div></div><div></div><div></div></div></div></div>';
  4.     Swal.fire({
  5.         title: 'Edit Bonding',
  6.         html: modalContent,
  7.         showCancelButton: true,
  8.         showLoaderOnConfirm: true,
  9.         confirmButtonText: 'Save',
  10.         cancelButtonText: 'Cancel',
  11.         didOpen: () => {
  12.             $.ajax({
  13.                 url: '/api/interfaces_list',
  14.                 type: 'POST',
  15.                 dataType: 'json',
  16.                 success: function(responseData) {
  17.                     jsonData = responseData;
  18.                     ethernetInterfaces = Object.keys(jsonData.data.interfaces.ethernet);
  19.  
  20.                     modalContent = createEditForm(data, ethernetInterfaces);
  21.                     Swal.update({ html: modalContent });
  22.                 },
  23.                 error: function(error) {
  24.                     Swal.update({ html: '<div>Error loading data.</div>', icon: 'error' });
  25.                     console.log('Error fetching data:', error);
  26.                 }
  27.             });
  28.         },
  29.       //   preConfirm: () => {
  30.       //     function getFormData() {
  31.       //       const bondMode = document.getElementById("bondMode").value;
  32.       //       const hashPolicy = document.getElementById("hashPolicy").value;
  33.       //       const slaveSelects = document.querySelectorAll(".slaveRow select");
  34.       //       let memberInterface;
  35.        
  36.       //       if (slaveSelects.length === 0) {
  37.       //           memberInterface = [null]; // Jika tidak ada select option, berikan nilai [null]
  38.       //       } else {
  39.       //           memberInterface = Array.from(slaveSelects).map(select => select.value);
  40.       //       }
  41.        
  42.       //       return {
  43.       //           bondMode: bondMode,
  44.       //           hashPolicy: hashPolicy,
  45.       //           memberInterface: memberInterface
  46.       //       };
  47.       //   }
  48.        
  49.        
  50.       //   const formData = getFormData();
  51.       //   const isBondModeChanged = formData.bondMode !== data.mode;
  52.       //   const isHashPolicyChanged = formData.hashPolicy !== data.hashPolicy;
  53.        
  54.       //   const originalMemberInterfaces = data.memberInterfaces.split(',').map(s => s.trim());
  55.       //   let isMembersChanged = !(originalMemberInterfaces.every((val, index) => val === formData.memberInterface[index])
  56.       //                               && originalMemberInterfaces.length === formData.memberInterface.length);
  57.    
  58.       //   const isMembersInitiallyEmpty = originalMemberInterfaces.length === 0 || (originalMemberInterfaces.length === 1 && originalMemberInterfaces[0] === "");
  59.       //   const isFormDataMembersEmpty = formData.memberInterface[0] === null;
  60.    
  61.       //   if (isMembersInitiallyEmpty && isFormDataMembersEmpty) {
  62.       //       isMembersChanged = false;
  63.       //   }
  64.    
  65.       //   if (!isBondModeChanged && !isHashPolicyChanged && !isMembersChanged) {
  66.       //     Swal.fire('No Changes', 'There are no changes to save.', 'info');
  67.       //     return false;
  68.       // }
  69.      
  70.       // // Mengganti nilai null menjadi "delete all"
  71.       // if (formData.memberInterface[0] === null) {
  72.       //     formData.memberInterface = ["deleteInterface"];
  73.       // }
  74.      
  75.       // // Mendefinisikan postData
  76.       // let postData = {
  77.       //     bondName: data.bondName,
  78.       //     bondMode: isBondModeChanged ? formData.bondMode : "",
  79.       //     hashPolicy: isHashPolicyChanged ? formData.hashPolicy : "",
  80.       //     bondMember: isMembersChanged ? formData.memberInterface : []
  81.       // };
  82.       //   console.log(postData);
  83.  
  84.       //       return fetch('/api/bonding_edit', {
  85.       //         method: "POST",
  86.       //         headers: {
  87.       //             "Content-Type": "application/json",
  88.       //         },
  89.       //         body: JSON.stringify({
  90.       //           bondName: data.bondName,
  91.       //           bondMode: isBondModeChanged ? formData.bondMode : "",
  92.       //           hashPolicy: isHashPolicyChanged ? formData.hashPolicy : "",
  93.       //           bondMember: isMembersChanged ? formData.memberInterface : []
  94.       //       })
  95.       //     })
  96.       //     .then((response) => {
  97.       //         if (!response.ok) {
  98.       //             throw new Error("Network response was not ok");
  99.       //         }
  100.       //         return response.json();
  101.       //     })
  102.       //     .then((data) => {
  103.       //         if (!data.success) {
  104.       //             throw new Error(data.message);
  105.       //         }
  106.       //         Swal.fire("Success!", data.message, "success");
  107.       //         $('#interfaces-bonding').DataTable().ajax.reload();
  108.       //         console.info(data);
  109.       //     })
  110.       //     .catch((error) => {
  111.       //         Swal.fire("Error!", error.message , "error");
  112.       //         console.error(error);
  113.       //     });
  114.        
  115.       //   }
  116.  
  117.       preConfirm: () => {
  118.         function getFormData() {
  119.             const bondMode = document.getElementById("bondMode").value;
  120.             const hashPolicy = document.getElementById("hashPolicy").value;
  121.             const slaveSelects = document.querySelectorAll(".slaveRow select");
  122.             let memberInterface;
  123.    
  124.             if (slaveSelects.length === 0) {
  125.                 memberInterface = [null]; // Jika tidak ada select option, berikan nilai [null]
  126.             } else {
  127.                 memberInterface = Array.from(slaveSelects).map(select => select.value);
  128.             }
  129.    
  130.             return {
  131.                 bondMode: bondMode,
  132.                 hashPolicy: hashPolicy,
  133.                 memberInterface: memberInterface
  134.             };
  135.         }
  136.    
  137.         const formData = getFormData();
  138.         const isBondModeChanged = formData.bondMode !== data.mode;
  139.         const isHashPolicyChanged = formData.hashPolicy !== data.hashPolicy;
  140.    
  141.         const originalMemberInterfaces = data.memberInterfaces.split(',').map(s => s.trim());
  142.         const formDataInterfaces = formData.memberInterface;
  143.    
  144.         let addedInterfaces = formDataInterfaces.filter(interface => !originalMemberInterfaces.includes(interface));
  145.         let removedInterfaces = originalMemberInterfaces.filter(interface => !formDataInterfaces.includes(interface));
  146.    
  147.         const isMembersChanged = addedInterfaces.length > 0 || removedInterfaces.length > 0;
  148.    
  149.         // // Mengganti nilai null menjadi "delete all"
  150.         // let formDataInterfacesCopy = [...formDataInterfaces]; // Buat salinan dari array formDataInterfaces
  151.         // if (formDataInterfacesCopy[0] === null) {
  152.         //     formDataInterfacesCopy = ["deleteInterface"];
  153.         // }
  154.  
  155.         // Hapus null dari addedInterfaces jika semua antarmuka dihapus
  156.         addedInterfaces = addedInterfaces.filter(interface => interface !== null);
  157.  
  158.         // Mendefinisikan postData
  159.         let postData = {
  160.             bondName: data.bondName,
  161.             bondMode: isBondModeChanged ? formData.bondMode : "",
  162.             hashPolicy: isHashPolicyChanged ? formData.hashPolicy : "",
  163.             bondMember: {
  164.                 add: addedInterfaces,
  165.                 delete: removedInterfaces
  166.             } // Objek dengan turunan add dan delete
  167.         };
  168.  
  169.         console.log(postData);
  170.  
  171.    
  172.         // Jika tidak ada perubahan, tampilkan pesan dan kembalikan false
  173.         if (!isMembersChanged) {
  174.             Swal.fire('No Changes', 'There are no changes to save.', 'info');
  175.             return false;
  176.         }
  177.    
  178.         return fetch('/api/bonding_edit', {
  179.                 method: "POST",
  180.                 headers: {
  181.                     "Content-Type": "application/json",
  182.                 },
  183.                 body: JSON.stringify(postData) // Kirim postData ke backend
  184.             })
  185.             .then((response) => {
  186.                 if (!response.ok) {
  187.                     throw new Error("Network response was not ok");
  188.                 }
  189.                 return response.json();
  190.             })
  191.             .then((data) => {
  192.                 if (!data.success) {
  193.                     throw new Error(data.message);
  194.                 }
  195.                 Swal.fire("Success!", data.message, "success");
  196.                 $('#interfaces-bonding').DataTable().ajax.reload();
  197.                 console.info(data);
  198.             })
  199.             .catch((error) => {
  200.                 Swal.fire("Error!", error.message, "error");
  201.                 console.error(error);
  202.             });
  203.    
  204.     }
  205.    
  206.    
  207.    
  208.    
  209.    
  210.  
  211.       })
  212.     }
  213.  
  214.  
  215.   function createEditForm(data, ethernetInterfaces) {
  216.     let modalContent = `
  217.         <div id="modalFormContainer">
  218.             <input type="text" id="bondName" class="mt-3 form-control" placeholder="${data.bondName}" disabled>
  219.     `;
  220.  
  221.     modalContent += `
  222.         <select id="bondMode" class="mt-3 form-select">
  223.     `;
  224.  
  225.     const bondModes = [
  226.         '802.3ad', 'active-backup', 'broadcast', 'round-robin', 'transmit-load-balance',
  227.         'adaptive-load-balance', 'xor-hash'
  228.     ];
  229.     bondModes.forEach(mode => {
  230.         modalContent += `
  231.             <option value="${mode}" ${data.mode === mode ? 'selected' : ''}>${mode}</option>
  232.         `;
  233.     });
  234.  
  235.     modalContent += '</select>';
  236.  
  237.     modalContent += `
  238.         <select id="hashPolicy" class="mt-3 form-select">
  239.     `;
  240.  
  241.     const hashPolicies = ['layer2', 'layer2+3', 'layer3+4', 'encap2+3', 'encap3+4'];
  242.     hashPolicies.forEach(policy => {
  243.         modalContent += `
  244.             <option value="${policy}" ${data.hashPolicy === policy ? 'selected' : ''}>${policy}</option>
  245.         `;
  246.     });
  247.  
  248.     modalContent += '</select>';
  249.     modalContent += `
  250.         <div class="input-group mt-3">
  251.             <button class="mt-3 btn btn-sm btn-outline-primary" type="button" onclick="tambahSlave(document.getElementById('modalFormContainer'))">+ Add Member Interface</button>
  252.         </div>
  253.     `;
  254.  
  255.     const slaveInterfaces = data.memberInterfaces.split(',').map(s => s.trim());
  256.     if (slaveInterfaces.length > 0 && slaveInterfaces[0] !== "") {
  257.         slaveInterfaces.forEach(item => {
  258.             modalContent += '<div class="slaveRow input-group mt-3"><select class="form-select">';
  259.             ethernetInterfaces.forEach(interface => {
  260.                 modalContent += `
  261.                     <option value="${interface}" ${item === interface ? 'selected' : ''}>${interface}</option>
  262.                 `;
  263.             });
  264.             modalContent += `
  265.                 </select>
  266.                 <button class="btn btn-outline-danger" onclick="hapusBaris(this)">-</button>
  267.                 </div>
  268.             `;
  269.         });
  270.     }
  271.    
  272.  
  273.     modalContent += '</div>';
  274.  
  275.     return modalContent;
  276.   }
  277.  
  278.   function tambahSlave(container) {
  279.         const newSelect = document.createElement('select');
  280.         newSelect.className = 'form-select';
  281.         const defaultOption = document.createElement('option');
  282.         defaultOption.value = "";
  283.         defaultOption.textContent = "-- Choose Interface --";
  284.         newSelect.appendChild(defaultOption);
  285.  
  286.         ethernetInterfaces.forEach(interface => {
  287.             const option = document.createElement('option');
  288.             option.value = interface;
  289.             option.textContent = interface;
  290.             newSelect.appendChild(option);
  291.         });
  292.  
  293.         const removeBtn = document.createElement('button');
  294.         removeBtn.className = 'btn btn-outline-danger';
  295.         removeBtn.textContent = '-';
  296.         removeBtn.onclick = function () {
  297.             hapusBaris(removeBtn);
  298.         };
  299.  
  300.         const newRow = document.createElement('div');
  301.         newRow.className = 'slaveRow input-group mt-3';
  302.         newRow.appendChild(newSelect);
  303.         newRow.appendChild(removeBtn);
  304.  
  305.         container.appendChild(newRow);
  306.   }
  307.  
  308.   function hapusBaris(button) {
  309.         const row = button.parentNode;
  310.         row.parentNode.removeChild(row);
  311.   }
  312.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement