Related to issue 17894.Added ability to mix gl items and invoices on payment in/out windows.
authorGorka Ion Damián <gorkaion.damian@openbravo.com>
Tue, 26 Jul 2011 11:42:56 +0200
changeset 13266 e251f7b1d594
parent 13265 24c312ba2766
child 13267 bc4bd502bc4d
Related to issue 17894.Added ability to mix gl items and invoices on payment in/out windows.
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddOrderOrInvoice.html
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddOrderOrInvoice.java
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddOrderOrInvoice.html	Tue Jul 26 11:40:27 2011 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddOrderOrInvoice.html	Tue Jul 26 11:42:56 2011 +0200
@@ -51,6 +51,10 @@
   window.onunload = reloadOpener; // reloads opener on closing
 </script>
 <script language="JavaScript" type="text/javascript">
+  OB.APRM = OB.APRM || {};
+  OB.APRM.APFT_GLItems = [];
+  OB.APRM.APFT_GLItemsId = 0;
+  OB.APRM.HasGLItems = false;
 var hasBPartner = null;
 </script>
 <script language="JavaScript" type="text/javascript">
@@ -104,84 +108,92 @@
     alert(e);
   }
 }
-function callBackGLItemGrid(paramXMLParticular, XMLHttpRequestObj) {
-  var strText = '';
-  if (getReadyStateHandler(XMLHttpRequestObj)) {
-    try {
-      if (XMLHttpRequestObj.responseText) {
-        strText = XMLHttpRequestObj.responseText;
-        var aux = strText.substring(29, strText.length-8);
-        var tableBody = document.getElementById('sectionGLItemGrid');
-        var browserName = getBrowserInfo('name');
-        if (browserName.toUpperCase().indexOf('INTERNET EXPLORER') !== -1) {
-          var temp = document.createElement('span');
-          temp.id = 'temp';
-          temp.style.display = 'none';
-          var newRows = '<table><tbody id=\"sectionGLItemGrid\">'+ aux;
-          temp.innerHTML = newRows;
-          tableBody.parentNode.replaceChild(temp.firstChild.firstChild, tableBody);
-          temp.parentNode.removeChild(temp);
-        }
-        tableBody.innerHTML = aux;
-            
-        updateGLItemTotal();
-      } else {
-        document.getElementById('sectionGLItemGrid').innerHTML = '';
-      }
-    } catch (e) {
+</script>
+<script language="JavaScript" type="text/javascript">
+function loadGLItemList() {
+  var table = document.getElementById('sectionGLItemGrid'),
+      glitemCount = OB.APRM.APFT_GLItems.length,
+      glitemAmount = 0,
+      rowCount, row, cellGLItemDesc, cellGLITemReceivedInAmt, cellGLITemPaidOutAmt, cellRemoveButton, i, textNode;
+
+  table.innerHTML = '';
+  if (glitemCount === 0) {
+    OB.APRM.HasGLItems = false;
+    return;
+  }
+  OB.APRM.HasGLItems = true;
+  for (i = 0; i < glitemCount; i++) {
+    rowCount = table.rows.length;
+    row = table.insertRow(rowCount);
+    row.className = 'DataGrid_Body_Row DataGrid_Body_Row_'+i%2;
+    
+    cellGLItemDesc = row.insertCell(0);
+    textNode = document.createTextNode(OB.APRM.APFT_GLItems[i].glitemDesc);
+    cellGLItemDesc.appendChild(textNode);
+    cellGLItemDesc.className = 'DataGrid_Body_Cell';
+    
+    cellGLITemReceivedInAmt = row.insertCell(1);
+    textNode = document.createTextNode(applyFormatJSToOBMasked(OB.APRM.APFT_GLItems[i].glitemReceivedInAmt));
+    cellGLITemReceivedInAmt.appendChild(textNode);
+    cellGLITemReceivedInAmt.className = 'DataGrid_Body_Cell_Amount';
+    
+    cellGLITemPaidOutAmt = row.insertCell(2);
+    textNode = document.createTextNode(applyFormatJSToOBMasked(OB.APRM.APFT_GLItems[i].glitemPaidOutAmt));
+    cellGLITemPaidOutAmt.appendChild(textNode);
+    cellGLITemPaidOutAmt.className = 'DataGrid_Body_Cell_Amount';
+    
+    if (isTrue('isReceipt')) {
+      glitemAmount = subtract(applyFormatJSToOBMasked(OB.APRM.APFT_GLItems[i].glitemReceivedInAmt), applyFormatJSToOBMasked(OB.APRM.APFT_GLItems[i].glitemPaidOutAmt));
+    } else {
+      glitemAmount = subtract(applyFormatJSToOBMasked(OB.APRM.APFT_GLItems[i].glitemPaidOutAmt), applyFormatJSToOBMasked(OB.APRM.APFT_GLItems[i].glitemReceivedInAmt));
     }
+    cellRemoveButton = row.insertCell(3);
+    cellRemoveButton.innerHTML = '<div><button type="button" id="buttonRemoveGLItem"'
+        + ' class="ButtonLink_focus" onclick="removeGLItem(' + i + ', ' + glitemAmount + ');return false;"'
+        + ' onfocus="buttonEvent(\'onfocus\', this); window.status=\'OK\'; return true;"'
+        + ' onblur="buttonEvent(\'onblur\', this);"'
+        + '  onkeyup="buttonEvent(\'onkeyup\', this);"'
+        + '  onkeydown="buttonEvent(\'onkeydown\', this);"'
+        + '  onkeypress="buttonEvent(\'onkeypress\', this);"'
+        + '  onmouseup="buttonEvent(\'onmouseup\', this);"'
+        + '  onmousedown="buttonEvent(\'onmousedown\', this);"'
+        + '  onmouseover="buttonEvent(\'onmouseover\', this); window.status=\'OK\'; return true;"'
+        + '  onmouseout="buttonEvent(\'onmouseout\', this);">'
+        + '  <table class="Button"><tr><td>'
+        + '    <img alt="Remove" title="Remove" src="../web/org.openbravo.advpaymentmngt/images/GLItemGridCancel-xButt.png" id="imgButtonRemove" border="0"/></td>'
+        + '  </tr></table></button></div>';
   }
-  return true;
-}
-function loadGLItemList() {
-  try {
-    var url = '../org.openbravo.advpaymentmngt.ad_actionbutton/AddOrderOrInvoice.html';
-    var paramXMLReq = null;
-    return submitXmlHttpRequest(callBackGLItemGrid, document.frmMain, 'GLITEMGRIDLIST', url, false, null, paramXMLReq);
-  } catch (e) {
-    alert(e);
-  }
-}
-function callBackGLItem(paramXMLParticular, XMLHttpRequestObj) {
-  var strText = '';
-  if (getReadyStateHandler(XMLHttpRequestObj)) {
-    try {
-      if (XMLHttpRequestObj.responseText) {
-        strText = XMLHttpRequestObj.responseText;
-        if (strText !== '' && strText !== '\r\n') {
-          setValues_MessageBox('messageBoxID', 'WARNING', '', strText);
-        } else {
-          initialize_MessageBox('messageBoxID');
-        }
-        if (paramXMLParticular !== null) {
-          closePage();
-          return true;
-        }
-        loadGLItemList();
-      } else {
-        initialize_MessageBox('messageBoxID');
-      }
-    } catch (e) {
-    }
-  }
-  return true;
+  updateTotal();
 }
 function addGLItem() {
-  if (frm.inpGLItemAmount.value === null || frm.inpGLItemAmount.value === '') {
-    setWindowElementFocus(frm.inpGLItemAmount);
+  var amount = 0, glamount = 0, expectedAmt = 0;
+  if (frm.inpGLItemReceivedInAmount.value === null || frm.inpGLItemReceivedInAmount.value === '') {
+    setWindowElementFocus(frm.inpGLItemReceivedInAmount);
+    showJSMessage(7);
+    return false;
+  } else if (frm.inpGLItemPaidOutAmount.value === null || frm.inpGLItemPaidOutAmount.value === '') {
+    setWindowElementFocus(frm.inpGLItemPaidOutAmount);
     showJSMessage(7);
     return false;
   } else if (frm.inpcGlitemId.value === null || frm.inpcGlitemId.value === '') {
     setWindowElementFocus(frm.inpcGlitemId);
     showJSMessage(7);
     return false;
+  } else if ( (compare(frm.inpGLItemReceivedInAmount.value, '==', 0) && compare(frm.inpGLItemPaidOutAmount.value, '==', 0)) ||
+              (compare(frm.inpGLItemReceivedInAmount.value, '!=', 0) && compare(frm.inpGLItemPaidOutAmount.value, '!=', 0)) ) {
+    setWindowElementFocus(frm.paramPaymentAmountGLItem);
+    showJSMessage('APRM_JSAMOUNTDIFFTOZERO');
+    return false;
   }
-
-  try {
-    var url = '../org.openbravo.advpaymentmngt.ad_actionbutton/AddOrderOrInvoice.html';
-    var paramXMLReq = null;
-    document.frmMain.inpGLSumAmount.value = add(document.frmMain.inpGLSumAmount.value, document.frmMain.inpGLItemAmount.value);
-    var amount = document.frmMain.inpGLSumAmount.value;
+  if (isTrue('isReceipt')) {
+    glamount = subtract(frm.inpGLItemReceivedInAmount.value, frm.inpGLItemPaidOutAmount.value);
+  } else {
+    glamount = subtract(frm.inpGLItemPaidOutAmount.value, frm.inpGLItemReceivedInAmount.value);
+  }
+  amount = add(document.frmMain.inpGLSumAmount.value, glamount);
+  document.frmMain.inpGLSumAmount.value = amount;
+  document.frmMain.inpExpectedPayment.value = add(document.frmMain.inpExpectedPayment.value, glamount);
+  if (!isTrue('isReceipt')) {
     if (document.frmMain.inpUseCredit.checked) {
       amount = subtract(amount, document.frmMain.inpCredit.value);
       if ( compare(amount, '<', '0') ) {
@@ -189,41 +201,40 @@
       }
     }
     document.frmMain.inpActualPayment.value = amount;
-    updateConvertedAmounts();
-    return submitXmlHttpRequest(callBackGLItem, document.frmMain, 'ADDGLITEM', url, false, null, paramXMLReq);
-  } catch (e) {
-    alert(e);
   }
+  OB.APRM.APFT_GLItemsId++;
+  OB.APRM.APFT_GLItems.push({
+    id: OB.APRM.APFT_GLItemsId,
+    glitemId: frm.inpcGlitemId.value,
+    glitemDesc: sc_C_Glitem_ID.selectorField.getDisplayValue(),
+    glitemReceivedInAmt: OB.Utilities.Number.OBMaskedToJS(frm.inpGLItemReceivedInAmount.value,
+                                                          getGlobalDecSeparator(),
+                                                          getGlobalGroupSeparator()),
+    glitemPaidOutAmt: OB.Utilities.Number.OBMaskedToJS(frm.inpGLItemPaidOutAmount.value,
+                                                       getGlobalDecSeparator(),
+                                                       getGlobalGroupSeparator())
+  });
+  loadGLItemList();
 }
-function removeGLItem(key) {
-  try {
-    document.frmMain.inpDeleteGLItem.value = key;
-    var url = '../org.openbravo.advpaymentmngt.ad_actionbutton/AddOrderOrInvoice.html';
-    var paramXMLReq = null;
-    if ( compare(document.frmMain.inpActualPayment.value, '>', document.frmMain.elements['inpHiddenAmt'+key].value) ) {
-      document.frmMain.inpActualPayment.value = subtract(document.frmMain.inpActualPayment.value, document.frmMain.elements['inpHiddenAmt'+key].value);
+function removeGLItem(key, removedAmount) {
+  if (!isTrue('isReceipt')){
+    if ( compare(document.frmMain.inpActualPayment.value, '>', removedAmount) ) {
+      document.frmMain.inpActualPayment.value = subtract(document.frmMain.inpActualPayment.value, removedAmount);
     } else {
       document.frmMain.inpActualPayment.value = 0;
     }
-    document.frmMain.inpGLSumAmount.value = subtract(document.frmMain.inpGLSumAmount.value, document.frmMain.elements['inpHiddenAmt'+key].value);
-    updateConvertedAmounts();
-    return submitXmlHttpRequest(callBackGLItem, document.frmMain, 'REMOVEGLITEM', url, false, null, paramXMLReq);
-  } catch (e) {
-    alert(e);
   }
+  document.frmMain.inpGLSumAmount.value = subtract(document.frmMain.inpGLSumAmount.value, removedAmount);
+  document.frmMain.inpExpectedPayment.value = subtract(document.frmMain.inpExpectedPayment.value, removedAmount);
+  OB.APRM.APFT_GLItems.splice(key, 1);
+  updateConvertedAmounts();
+  loadGLItemList();
 }
 function removeAllGLItem(closePopup) {
-  try {
-    document.frmMain.inpDeleteGLItem.value = '';
-    var url = '../org.openbravo.advpaymentmngt.ad_actionbutton/AddOrderOrInvoice.html';
-    var paramXMLReq = closePopup ? closePopup : null;
-    return submitXmlHttpRequest(callBackGLItem, document.frmMain, 'REMOVEALLGLITEM', url, false, null, paramXMLReq);
-  } catch (e) {
-    alert(e);
-  }
+  OB.APRM.APFT_GLItems = [];
+  loadGLItemList();
   updateConvertedAmounts();
 }
-
 function displayMulticurrencyControls() {
   var invCurrency = document.getElementById('paramCurrencyId').value
   var accountCurrency = document.getElementById('paramFinancialAccountCurrencyId').value
@@ -232,8 +243,6 @@
 
   displayLogicElement('multiCurrencyRow', display );
 }
-
-
 </script>
 <script language="JavaScript" type="text/javascript">
 function validate(action) {
@@ -243,9 +252,6 @@
       setWindowElementFocus(frm.inpActualPayment);
       showJSMessage(7);
       return false;
-    } else if (isTrue('isGLItem')) {
-      //Do nothing on case of GL Item.
-      return true;
     } else {
       var diffAction = frm.inpDifferenceAction,
           selectedAction = null, i, actionSelected = false;
@@ -263,46 +269,6 @@
   }
   return true;
 }
-function setGLItemMode(toGLItem){
-  if (isTrue('isReceipt')) {
-    if (toGLItem){
-      document.getElementById('paramActualPayment').className.replace(' readonly', '');
-      document.getElementById('paramActualPayment').readOnly = true;
-      var classText = document.getElementById('paramActualPayment').className;
-      document.getElementById('paramActualPayment').className = classText.concat(' readonly');
-      displayLogicElement('NoPackageslinkCalc', false);
-    } else {
-      var classTextReadOnly = document.getElementById('paramActualPayment').className.replace(' readonly', '');
-      document.getElementById('paramActualPayment').className = classTextReadOnly;
-      document.getElementById('paramActualPayment').readOnly = false;
-      displayLogicElement('NoPackageslinkCalc', true);
-    }
-  }
-
-  displayLogicElement('glitemBlank', toGLItem);
-  displayLogicElement('glitemBlank', toGLItem);
-  displayLogicElement('glitemRow', toGLItem);
-  displayLogicElement('glitemAddRow', toGLItem);
-  displayLogicElement('DueDateFromLbl', !toGLItem);
-  displayLogicElement('DueDateFrom', !toGLItem);
-  displayLogicElement('DueDateToLbl', !toGLItem);
-  displayLogicElement('DueDateTo', !toGLItem);
-  displayLogicElement('gridPayment', !toGLItem);
-  displayLogicElement('gridGLItem', toGLItem);
-  displayLogicElement('inpAlternativeLabel', !toGLItem);
-  displayLogicElement('inpAlternativeChkBox', !toGLItem);
-  if (toGLItem) {
-    displayLogicElement('bpartnerfilterRow', !toGLItem);
-  } else {
-    displayLogicElement('bpartnerfilterRow', !hasBPartner);
-  }
-
-  resizeAreaCreateFrom();
-  if (toGLItem) {
-    loadGLItemList();
-  }
-  return true;
-}
 function updateData(key, mark, drivenByGrid) {
   if (mark === null) { mark=false; }
   updateReadOnly(key, mark);
@@ -356,49 +322,63 @@
   updateTotal();
   numberInputEvent('onchange', element);
 }
+function setGLItemMode(toGLItem){
+  displayLogicElement('glitemRow', toGLItem);
+  displayLogicElement('glitemAddRow', toGLItem);
+  displayLogicElement('gridGLItem', toGLItem);
+  displayLogicElement('totalInvoices', toGLItem);
+  displayLogicElement('GLItemSelectorLbl', toGLItem);
+  displayLogicElement('GLItemSelector', toGLItem);
+  
+  displayLogicElement('DueDateFromLbl', !toGLItem);
+  displayLogicElement('DueDateFrom', !toGLItem);
+  displayLogicElement('DueDateToLbl', !toGLItem);
+  displayLogicElement('DueDateTo', !toGLItem);
+  displayLogicElement('gridPayment', !toGLItem);
+  displayLogicElement('totalGLItems', !toGLItem);
+  displayLogicElement('inpAlternativeLabel', !toGLItem);
+  displayLogicElement('inpAlternativeChkBox', !toGLItem);
+  if (toGLItem) {
+    displayLogicElement('bpartnerfilterRow', !toGLItem);
+  } else {
+    displayLogicElement('bpartnerfilterRow', !hasBPartner);
+  }
+
+  resizeAreaCreateFrom();
+  if (toGLItem) {
+    loadGLItemList();
+  }
+  return true;
+}
 function documentTypeOnChange(value){
   if ('G' === value) {
-    if (!isTrue('isGLItem')) {
-      document.frmMain.isGLItem.value='Y';
+    //if we are not already on GL Item mode.
+    if (!isTrue('isInGLItemMode')) {
+      document.frmMain.isInGLItemMode.value='Y';
+      document.getElementById('paramInvoicesAmt').innerHTML = frm.inpInvoiceAmount.value;
       setGLItemMode(true);
-      document.frmMain.inpHeaderAmount.value = document.frmMain.inpActualPayment.value;
-      var amount = document.frmMain.inpGLSumAmount.value;
-      if (document.frmMain.inpUseCredit.checked) {
-        amount = subtract(amount, document.frmMain.inpCredit.value);
-        if ( compare(amount, '<', '0') ) {
-          amount = 0;
-        }
-      }
-      document.frmMain.inpActualPayment.value = amount;
     }
   } else {
-    document.frmMain.inpActualPayment.value=document.frmMain.inpHeaderAmount.value;
+    document.getElementById('paramGLItemsAmt').innerHTML = document.frmMain.inpGLSumAmount.value;
     document.frmMain.isFirstLoad.value = 'true';
+    if (isTrue('isInGLItemMode')) {
+      document.frmMain.isInGLItemMode.value='N';
+      setGLItemMode(false);
+    }
     loadGridList();
-    if (isTrue('isGLItem')) {
-      document.frmMain.isGLItem.value='N';
-      setGLItemMode(false);
-      updateTotal();
-    }
   }
 }
 function actualPaymentOnChange(){
-  var amount = null;
-  if (isTrue('isReceipt') && !isTrue('isGLItem')) {
-    amount = document.frmMain.inpActualPayment.value;
+  if (isTrue('isReceipt')) {
+    var amount = document.frmMain.inpActualPayment.value;
     if (document.frmMain.inpUseCredit.checked) {
       amount = add(amount, document.frmMain.inpCredit.value);
     }
-    distributeAmount(amount);
-  } else if (isTrue('isGLItem')) {
-    amount = document.frmMain.inpGLSumAmount.value;
-    if (document.frmMain.inpUseCredit.checked) {
-      amount = subtract(amount, document.frmMain.inpCredit.value);
-      if ( compare(amount, '<', '0') ) {
-        amount = 0;
-      }
+    if (isTrue('isInGLItemMode')) {
+      updateTotal();
+    } else {
+      distributeAmount(amount);
     }
-    document.frmMain.inpActualPayment.value=amount;
   }
 }
 function useCreditOnChange(){
@@ -419,11 +399,11 @@
   setBrowserAutoComplete(false);
   hasBPartner = document.frmMain.inpBusinessPartnerId.value !== null && document.frmMain.inpBusinessPartnerId.value !== '';
 
-  initFIN_Utilities(document.frmMain, hasBPartner);
+  initFIN_Utilities(document.frmMain, hasBPartner, null, true);
   try {
     onloadFunctions();
   } catch (e) {}
-  setGLItemMode(isTrue('isGLItem'));
+  setGLItemMode(isTrue('isInGLItemMode'));
   displayLogicElement('sectionDifference', false);
   displayLogicElement('sectionDifferenceBox', false);
   processLabels();
@@ -461,10 +441,7 @@
 }
 function submitThisPage(strCommand) {
   if (validate(strCommand)) {
-    if (isTrue('isGLItem')) {
-      var temp = document.getElementById('sectionGrid');
-      temp.parentNode.removeChild(temp);
-    }
+    document.frmMain.inpGLItems.value = isc.JSON.encode(OB.APRM.APFT_GLItems);
     submitCommandForm(strCommand, false, null, null);
     return true;
   }
@@ -490,7 +467,7 @@
   document.getElementById('client_top').style.display = 'block';
   document.getElementById('client_middle').style.display = 'block';
   document.getElementById('client_bottom').style.display = 'block';
-  setGLItemMode(isTrue('isGLItem'));
+  setGLItemMode(isTrue('isInGLItemMode'));
 }
 </script>
 </head>
@@ -505,10 +482,9 @@
   <input type="hidden" name="isReceipt" value="" id="fieldReceipt"/>
   <input type="hidden" name="inpissotrx" value="" id="fieldIsSoTrx"/>
   <input type="hidden" name="isFirstLoad" value="true"/>
-  <input type="hidden" name="isGLItem" value="N"/>
+  <input type="hidden" name="isInGLItemMode" value="N"/>
+  <input type="hidden" name="inpGLItems" value=""/>
   <input type="hidden" name="inpDeleteGLItem" value=""/>
-  <input type="hidden" id="paramHeaderAmount" name="inpHeaderAmount" value="0"/>
-  <input type="hidden" id="paramGLSumAmount" name="inpGLSumAmount" value="0"/>
   <input type="hidden" id="paramGeneratedCredit" name="inpGeneratedCredit" value="0"/>
   <div class="Popup_ContentPane_CircleLogo">
     <div class="Popup_WindowLogo">
@@ -866,8 +842,7 @@
                   <option value="G">GL Items</option>
                 </select>
               </td>
-              <td class="TitleCell"></td>
-              <td class="TitleCell" id="DueDateFromLbl"><span class="LabelText">Due Date From</span></td>
+              <td class="TitleCell" id="DueDateFromLbl" colspan="2"><span class="LabelText">Due Date From</span></td>
               <td class="TextBox_btn_ContentCell" id="DueDateFrom">
                 <table border="0" cellspacing="0" cellpadding="0" summary=""  style="padding-top: 0px;">
                   <tr>
@@ -898,7 +873,18 @@
                   </tr>
                 </table>
               </td>
-              <td class="TitleCell"></td>
+              <td class="TitleCell" id="GLItemSelectorLbl"><span class="LabelText">GL Item</span></td>
+              <td class="TextBox_ContentCell" colspan="2" id="GLItemSelector">
+                <table style="border:0px;border-collapse:collapse;">
+                  <tr>
+                    <td style="padding-top: 0px;">
+                      <script>var sc_C_Glitem_ID = null;</script>
+                      <input type="hidden" name="inpcGlitemId" id="C_Glitem_ID" value="" onreset="sc_C_Glitem_ID.resetSelector();" onchange="openbravo.Utilities.updateSmartClientComponentValue(this, sc_C_Glitem_ID.selectorField);"></input>
+                      <script id="selectorLink" src="../org.openbravo.client.kernel/OBUISEL_Selector/9FAD469CE4414A25974CF45C0AD22D35?columnName=C_Glitem_ID&disabled=false&CssSize=TwoCells&DisplayLength=45.0&required=true"></script>
+                    </td>
+                  </tr>
+                </table>
+              </td>
             </tr>
             <tr>
               <td class="TitleCell" id="inpAlternativeLabel"><span class="TitleCell LabelText"><label name="lblP" id="lblPShowPaym" for="paramAlternativePaymentMethod">Show payments out for alternative payment methods</label></span><span class="TitleCell LabelText"><label name="lblR" id="lblRShowPaym" for="paramAlternativePaymentMethod">Show payments in for alternative payment methods</label></span></td>
@@ -957,41 +943,65 @@
               <td class="TitleCell"></td>
             </tr>
             <tr id="glitemRow">
-              <td class="TitleCell"><span class="LabelText">GL Item</span></td>
-              <td class="TextBox_ContentCell" colspan="2">
-                <table style="border:0px;border-collapse:collapse;">
-                  <tr>
-                    <td style="padding-top: 0px;">
-                      <script>var sc_C_Glitem_ID = null;</script>
-                      <input type="hidden" name="inpcGlitemId" id="C_Glitem_ID" value="" onreset="sc_C_Glitem_ID.resetSelector();" onchange="openbravo.Utilities.updateSmartClientComponentValue(this, sc_C_Glitem_ID.selectorField);"></input>
-                      <script id="selectorLink" src="../org.openbravo.client.kernel/OBUISEL_Selector/9FAD469CE4414A25974CF45C0AD22D35?columnName=C_Glitem_ID&disabled=false&CssSize=TwoCells&DisplayLength=45.0&required=true"></script>
-                    </td>
-                  </tr>
-                </table>
-              </td>
-              <td class="TitleCell"><span name="lblR" id="lblRReceivedIn" class="LabelText">Received In</span><span name="lblP" id="lblPPaidOut" class="LabelText">Paid Out</span></td>
+              <td class="TitleCell"><span class="LabelText">Received In</span></td>
               <td class="TextBox_btn_ContentCell">
                 <table border="0" cellspacing="0" cellpadding="0" summary=""  style="padding-top: 0px;">
                   <tr>
                     <td class="Textbox_ContentCell">
                       <table style="border: 0px none; border-collapse: collapse;">
                         <tr><td style="padding-top: 0px;">
-                        <input type="text" id="paramGLItemAmount" class="dojoValidateValid required TextBox_btn_OneCell_width number"  value="0" maxlength="22" name="inpGLItemAmount" onblur="numberInputEvent('onblur', this);" onfocus="numberInputEvent('onfocus', this);" onchange="" oncontextmenu="changeToEditingMode('oncontextmenu');" onpaste="changeToEditingMode('onpaste');" oncut="changeToEditingMode('oncut');" onkeypress="changeToEditingMode('onkeypress');" onkeydown="changeToEditingMode('onkeydown'); numberInputEvent('onkeydown', this, event);" onkeyup="" outputformat="euroEdition"></input>
+                        <input type="text" id="paramGLItemReceivedInAmount" class="dojoValidateValid required TextBox_btn_OneCell_width number"  value="0" maxlength="22" name="inpGLItemReceivedInAmount" onblur="numberInputEvent('onblur', this);" onfocus="numberInputEvent('onfocus', this);" onchange="" oncontextmenu="changeToEditingMode('oncontextmenu');" onpaste="changeToEditingMode('onpaste');" oncut="changeToEditingMode('oncut');" onkeypress="changeToEditingMode('onkeypress');" onkeydown="changeToEditingMode('onkeydown'); numberInputEvent('onkeydown', this, event);" onkeyup="" outputformat="euroEdition"></input>
                         </td></tr>
                       </table>
-                      <span id="paramGLItemAmountinvalidSpan" style="display: none;" class="TextBox_MsgContainer_span">
+                      <span id="paramGLItemReceivedInAmountinvalidSpan" style="display: none;" class="TextBox_MsgContainer_span">
                         <table class="TextBox_MsgContainer_table">
                           <tbody><tr class="TextBox_MsgContainer_tr">
                             <td class="TextBox_MsgContainer_td"><div class="TextBox_MsgContainer_div"></div></td><td></td>
                           </tr>
                           <tr>
-                            <td class="invalid" colspan="2"><div name="invalidText" id="paramGLItemAmountinvalidSpanText" class="TextBox_MsgContainer_div2">* The value entered is not valid.</div></td>
+                            <td class="invalid" colspan="2"><div name="invalidText" id="paramGLItemReceivedInAmountinvalidSpanText" class="TextBox_MsgContainer_div2">* The value entered is not valid.</div></td>
                           </tr>
                         </tbody></table>
                       </span>
                     </td>
                     <td class="FieldButton_ContentCell">
-                      <a class="FieldButtonLink" href="#" onfocus="setWindowElementFocus(this); window.status='Amount'; return true;" onblur=" window.status=''; return true;" onkeypress="this.className='FieldButtonLink_active'; return true;" onkeyup="this.className='FieldButtonLink_focus'; return true;"  onclick="calculator('frmMain.inpGLItemAmount', document.frmMain.inpGLItemAmount.value, false);return false;">
+                      <a class="FieldButtonLink" href="#" onfocus="setWindowElementFocus(this); window.status='Amount'; return true;" onblur=" window.status=''; return true;" onkeypress="this.className='FieldButtonLink_active'; return true;" onkeyup="this.className='FieldButtonLink_focus'; return true;"  onclick="calculator('frmMain.inpGLItemReceivedInAmount', document.frmMain.inpGLItemReceivedInAmount.value, false);return false;">
+                        <table class="FieldButton" onmouseout="this.className='FieldButton';window.status='';return true;" onmouseover="this.className='FieldButton_hover';window.status='';return true;" onmousedown="this.className='FieldButton_active';return true;" onmouseup="this.className='FieldButton';return true;" id="NoPackageslinkCalc">
+                          <tr>
+                            <td class="FieldButton_bg">
+                              <img alt="Calculator" class="FieldButton_Icon FieldButton_Icon_Calc" title="Amount" src="../../../../../web/images/blank.gif" border="0" id="buttonCalc"></img>
+                            </td>
+                          </tr>
+                        </table>
+                      </a>
+                    </td>
+                  </tr>
+                </table>
+              </td>
+              <td class="TitleCell"></td>
+              <td class="TitleCell"><span class="LabelText">Paid Out</span></td>
+              <td class="TextBox_btn_ContentCell">
+                <table border="0" cellspacing="0" cellpadding="0" summary=""  style="padding-top: 0px;">
+                  <tr>
+                    <td class="Textbox_ContentCell">
+                      <table style="border: 0px none; border-collapse: collapse;">
+                        <tr><td style="padding-top: 0px;">
+                        <input type="text" id="paramGLItemPaidOutAmount" class="dojoValidateValid required TextBox_btn_OneCell_width number"  value="0" maxlength="22" name="inpGLItemPaidOutAmount" onblur="numberInputEvent('onblur', this);" onfocus="numberInputEvent('onfocus', this);" onchange="" oncontextmenu="changeToEditingMode('oncontextmenu');" onpaste="changeToEditingMode('onpaste');" oncut="changeToEditingMode('oncut');" onkeypress="changeToEditingMode('onkeypress');" onkeydown="changeToEditingMode('onkeydown'); numberInputEvent('onkeydown', this, event);" onkeyup="" outputformat="euroEdition"></input>
+                        </td></tr>
+                      </table>
+                      <span id="paramGLItemPaidOutAmountinvalidSpan" style="display: none;" class="TextBox_MsgContainer_span">
+                        <table class="TextBox_MsgContainer_table">
+                          <tbody><tr class="TextBox_MsgContainer_tr">
+                            <td class="TextBox_MsgContainer_td"><div class="TextBox_MsgContainer_div"></div></td><td></td>
+                          </tr>
+                          <tr>
+                            <td class="invalid" colspan="2"><div name="invalidText" id="paramGLItemPaidOutAmountinvalidSpanText" class="TextBox_MsgContainer_div2">* The value entered is not valid.</div></td>
+                          </tr>
+                        </tbody></table>
+                      </span>
+                    </td>
+                    <td class="FieldButton_ContentCell">
+                      <a class="FieldButtonLink" href="#" onfocus="setWindowElementFocus(this); window.status='Amount'; return true;" onblur=" window.status=''; return true;" onkeypress="this.className='FieldButtonLink_active'; return true;" onkeyup="this.className='FieldButtonLink_focus'; return true;"  onclick="calculator('frmMain.inpGLItemPaidOutAmount', document.frmMain.inpGLItemPaidOutAmount.value, false);return false;">
                         <table class="FieldButton" onmouseout="this.className='FieldButton';window.status='';return true;" onmouseover="this.className='FieldButton_hover';window.status='';return true;" onmousedown="this.className='FieldButton_active';return true;" onmouseup="this.className='FieldButton';return true;" id="NoPackageslinkCalc">
                           <tr>
                             <td class="FieldButton_bg">
@@ -1045,7 +1055,7 @@
     <tr>
       <td>
         <div class="Popup_ContentPane_Client" style="overflow: auto;" id="client_middle">
-          <table height="100%" border="0" cellpadding="0" cellspacing="0" id="gridPayment">
+          <table height="100%" border="0" cellpadding="0" cellspacing="0">
             <tr>
               <td valign="top" class="Popup_Client_Selector_DataGrid_LeftMargin">
                 <table width="100%" border="0" cellspacing="0" cellpadding="0" id="tdleftSeparator">
@@ -1054,7 +1064,7 @@
               </td>
               <td valign="top">
                 <div id="client2" style="overflow: auto;">
-                  <table cellspacing="0" cellpadding="0" width="100%" class="DataGrid_Header_Table DataGrid_Body_Table" style="table-layout: auto;">
+                  <table cellspacing="0" cellpadding="0" width="100%" class="DataGrid_Header_Table DataGrid_Body_Table" style="table-layout: auto;" id="gridPayment">
                     <thead>
                       <tr class="DataGrid_Body_Row">
                         <th class="DataGrid_Header_LineNoCell DataGrid_Body_Cell_CheckBox" width="25"> 
@@ -1074,10 +1084,33 @@
                     <tbody id="sectionGrid">
                     </tbody>
                   </table>
+                  <table cellspacing="0" cellpadding="0" width="100%" class="DataGrid_Header_Table DataGrid_Body_Table" style="table-layout: auto;" id="gridGLItem">
+                    <thead>
+                      <tr class="DataGrid_Body_Row">
+                        <th class="DataGrid_Header_Cell" width="400">GL Item</th>
+                        <th class="DataGrid_Header_Cell DataGrid_Header_Cell_Inverse" width="100">Received In</th>
+                        <th class="DataGrid_Header_Cell DataGrid_Header_Cell_Inverse" width="100">Paid Out</th>
+                        <th class="DataGrid_Header_LineNoCell" width="20"></th>
+                      </tr>
+                    </thead>
+                    <tbody id="sectionGLItemGrid">
+                    </tbody>
+                  </table>
+                  
+                  <input type="hidden" name="inpGLSumAmount" value="0" outputformat="euroEdition"/>
+                  <input type="hidden" name="inpInvoiceAmount" value="0" outputformat="euroEdition"/>
                   <input type="hidden" id="inpTotal" value="0" outputformat="euroEdition"/>
                   <input type="hidden" name="inpDifference" id="inpDifference" value="0" outputformat="euroEdition"/>
                   <table cellspacing="0" cellpadding="0" width="100%" class="" style="table-layout: auto;">
                     <tr class="FieldGroup_BottomMargin"></tr>
+                    <tr id="totalInvoices">
+                      <td width="80%" class="LabelText" style="text-align:right">Amount on Invoices and/or Orders</td>
+                      <td class="LabelText number" style="padding-right:10px;font-weight: bold;"><span id="paramInvoicesAmt"></span></td>
+                    </tr>
+                    <tr id="totalGLItems">
+                      <td width="80%" class="LabelText" style="text-align:right">Amount on GL Items</td>
+                      <td class="LabelText number" style="padding-right:10px;font-weight: bold;"><span id="paramGLItemsAmt"></span></td>
+                    </tr>
                     <tr>
                       <td width="80%" class="LabelText" style="text-align:right">Total</td>
                       <td class="LabelText number" style="padding-right:10px;font-weight: bold;"><span id="paramTotal"></span></td>
@@ -1128,35 +1161,6 @@
             </tr>
             
           </table>
-          <table height="100%" border="0" cellpadding="0" cellspacing="0" id="gridGLItem">
-            <tr>
-              <td valign="top" class="Popup_Client_Selector_DataGrid_LeftMargin">
-                <table width="100%" border="0" cellspacing="0" cellpadding="0" id="tdleftSeparator">
-                  <tr><td class="Popup_Client_Selector_DataGrid_LeftMargin"></td></tr>
-                </table>
-              </td>
-              <td valign="top">
-                <div id="client2" style="overflow: auto;">
-                  <table cellspacing="0" cellpadding="0" width="100%" class="DataGrid_Header_Table DataGrid_Body_Table" style="table-layout: auto;">
-                    <thead>
-                      <tr class="DataGrid_Body_Row">
-                        <th class="DataGrid_Header_Cell" width="400">GL Item</th>
-                        <th class="DataGrid_Header_Cell DataGrid_Header_Cell_Inverse" width="200"><span name="lblR" id="lblRRecIn">Received In</span><span name="lblP" id="lblPPOut">Paid Out</span></th>
-                        <th class="DataGrid_Header_LineNoCell" width="20"></th>
-                      </tr>
-                    </thead>
-                    <tbody id="sectionGLItemGrid">
-                    </tbody>
-                  </table>
-                </div>
-              </td>
-              <td valign="top" class="Popup_Client_Selector_DataGrid_RightMargin">
-                <table width="100%" border="0" cellspacing="0" cellpadding="0" id="tdrightSeparator">
-                  <tr><td class="Popup_Client_Selector_DataGrid_RightMargin"></td></tr>
-                </table>
-              </td>
-            </tr>
-          </table>
         </div>
       </td>
     </tr>
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddOrderOrInvoice.java	Tue Jul 26 11:40:27 2011 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddOrderOrInvoice.java	Tue Jul 26 11:42:56 2011 +0200
@@ -29,6 +29,9 @@
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.process.FIN_AddPayment;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
@@ -50,7 +53,6 @@
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.financialmgmt.gl.GLItem;
 import org.openbravo.model.financialmgmt.payment.FIN_Payment;
-import org.openbravo.model.financialmgmt.payment.FIN_PaymentDetail;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
 import org.openbravo.xmlEngine.XmlDocument;
 
@@ -90,53 +92,6 @@
 
       printGrid(response, vars, strBusinessPartnerId, strPaymentId, strOrgId, strDueDateFrom,
           strDueDateTo, strDocumentType, strSelectedPaymentDetails, isReceipt, showAlternativePM);
-    } else if (vars.commandIn("GLITEMGRIDLIST")) {
-      String strPaymentId = vars.getRequestGlobalVariable("inpfinPaymentId", "");
-
-      printGLItemGrid(response, strPaymentId);
-
-    } else if (vars.commandIn("ADDGLITEM")) {
-      String strPaymentId = vars.getRequestGlobalVariable("inpfinPaymentId", "");
-      String strGLItemId = vars.getRequestGlobalVariable("inpcGlitemId", "");
-      String strGLItemAmount = vars.getRequiredNumericParameter("inpGLItemAmount", "0");
-
-      String errorMessage = "";
-      try {
-        FIN_AddPayment.saveGLItem(dao.getObject(FIN_Payment.class, strPaymentId), new BigDecimal(
-            strGLItemAmount), dao.getObject(GLItem.class, strGLItemId));
-      } catch (Exception e) {
-        errorMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage())
-            .getMessage();
-        log4j.error(e);
-      }
-      printGLItem(response, errorMessage);
-    } else if (vars.commandIn("REMOVEGLITEM")) {
-      String strPaymentId = vars.getRequestGlobalVariable("inpfinPaymentId", "");
-      String strPaymentDetailId = vars.getRequestGlobalVariable("inpDeleteGLItem", "");
-
-      String errorMessage = "";
-      try {
-        FIN_AddPayment.removeGLItem(dao.getObject(FIN_Payment.class, strPaymentId),
-            dao.getObject(FIN_PaymentDetail.class, strPaymentDetailId));
-      } catch (Exception e) {
-        errorMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage())
-            .getMessage();
-        log4j.error(e);
-      }
-      printGLItem(response, errorMessage);
-    } else if (vars.commandIn("REMOVEALLGLITEM")) {
-      String strPaymentId = vars.getRequestGlobalVariable("inpfinPaymentId", "");
-
-      String errorMessage = "";
-      try {
-        FIN_AddPayment.removeGLItem(dao.getObject(FIN_Payment.class, strPaymentId), null);
-      } catch (Exception e) {
-        errorMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage())
-            .getMessage();
-        log4j.error(e);
-      }
-      printGLItem(response, errorMessage);
-
     } else if (vars.commandIn("SAVE") || vars.commandIn("SAVEANDPROCESS")) {
       boolean isReceipt = vars.getRequiredStringParameter("isReceipt").equals("Y");
       String strAction = null;
@@ -149,6 +104,16 @@
       String strPaymentId = vars.getRequiredStringParameter("inpfinPaymentId");
       String strSelectedScheduledPaymentDetailIds = vars.getInParameter(
           "inpScheduledPaymentDetailId", "", IsIDFilter.instance);
+      String strAddedGLItems = vars.getStringParameter("inpGLItems");
+      JSONArray addedGLITemsArray = null;
+      try {
+        addedGLITemsArray = new JSONArray(strAddedGLItems);
+      } catch (JSONException e) {
+        log4j.error("Error parsing received GLItems JSON Array: " + strAddedGLItems, e);
+        bdErrorGeneralPopUp(request, response, "Error",
+            "Error parsing received GLItems JSON Array: " + strAddedGLItems);
+        return;
+      }
       String strDifferenceAction = "";
       BigDecimal refundAmount = BigDecimal.ZERO;
       String strDifference = vars.getNumericParameter("inpDifference", "0");
@@ -169,10 +134,6 @@
       // removed when new security implementation is done
       OBContext.setAdminMode();
       try {
-        // Remove GL Items
-        if (!"G".equals(strDocumentType)) {
-          FIN_AddPayment.removeGLItem(dao.getObject(FIN_Payment.class, strPaymentId), null);
-        }
 
         List<FIN_PaymentScheduleDetail> selectedPaymentDetails = FIN_Utility.getOBObjectList(
             FIN_PaymentScheduleDetail.class, strSelectedScheduledPaymentDetailIds);
@@ -184,6 +145,22 @@
         if (newPaymentAmount.compareTo(payment.getAmount()) != 0) {
           payment.setAmount(newPaymentAmount);
         }
+
+        if (addedGLITemsArray != null) {
+          for (int i = 0; i < addedGLITemsArray.length(); i++) {
+            JSONObject glItem = addedGLITemsArray.getJSONObject(i);
+            BigDecimal glItemOutAmt = new BigDecimal(glItem.getString("glitemPaidOutAmt"));
+            BigDecimal glItemInAmt = new BigDecimal(glItem.getString("glitemReceivedInAmt"));
+            BigDecimal glItemAmt = BigDecimal.ZERO;
+            if (isReceipt) {
+              glItemAmt = glItemInAmt.subtract(glItemOutAmt);
+            } else {
+              glItemAmt = glItemOutAmt.subtract(glItemInAmt);
+            }
+            FIN_AddPayment.saveGLItem(payment, glItemAmt,
+                dao.getObject(GLItem.class, glItem.getString("glitemId")));
+          }
+        }
         FIN_AddPayment.setFinancialTransactionAmountAndRate(payment, exchangeRate, convertedAmount);
         payment = FIN_AddPayment.savePayment(payment, isReceipt, null, null, null, null, null,
             null, null, null, null, selectedPaymentDetails, selectedPaymentDetailAmounts,
@@ -227,6 +204,15 @@
             }
           }
         }
+      } catch (Exception ex) {
+        String strMessage = FIN_Utility.getExceptionMessage(ex);
+        if (message != null && "Error".equals(message.getType())) {
+          strMessage = message.getMessage();
+        }
+        bdErrorGeneralPopUp(request, response, "Error", strMessage);
+        OBDal.getInstance().rollbackAndClose();
+        return;
+
       } finally {
         OBContext.restorePreviousMode();
       }
@@ -379,52 +365,6 @@
     out.close();
   }
 
-  private void printGLItemGrid(HttpServletResponse response, String strPaymentId)
-      throws IOException, ServletException {
-    dao = new AdvPaymentMngtDao();
-
-    log4j.debug("Output: Grid with GLItem payment details");
-
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
-        "org/openbravo/advpaymentmngt/ad_actionbutton/PaymentGLItemGrid").createXmlDocument();
-    // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
-    // removed when new security implementation is done
-    OBContext.setAdminMode();
-    try {
-
-      final List<FIN_PaymentDetail> paymentDetails = dao.getObject(FIN_Payment.class, strPaymentId)
-          .getFINPaymentDetailList();
-
-      FIN_PaymentDetail[] paymentDetailArray = new FIN_PaymentDetail[0];
-      paymentDetailArray = paymentDetails.toArray(paymentDetailArray);
-
-      FieldProvider[] data = FieldProviderFactory.getFieldProviderArray(paymentDetails);
-      for (int i = 0; i < data.length; i++) {
-        FieldProviderFactory.setField(data[i], "cglitemid",
-            paymentDetailArray[i].getGLItem() != null ? paymentDetailArray[i].getGLItem()
-                .getIdentifier() : "");
-        FieldProviderFactory.setField(data[i], "amount", paymentDetailArray[i].getAmount()
-            .toString());
-        FieldProviderFactory.setField(data[i], "finpaymentdetailid", paymentDetailArray[i].getId());
-      }
-
-      xmlDocument.setData("structure", (data == null) ? set() : data);
-      response.setContentType("text/html; charset=UTF-8");
-      PrintWriter out = response.getWriter();
-      out.println(xmlDocument.print());
-      out.close();
-    } finally {
-      OBContext.restorePreviousMode();
-    }
-  }
-
-  private void printGLItem(HttpServletResponse response, String errorMessage) throws IOException {
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(errorMessage);
-    out.close();
-  }
-
   private FieldProvider[] set() throws ServletException {
     HashMap<String, String> empty = new HashMap<String, String>();
     empty.put("finScheduledPaymentId", "");