Fixed issue 25696 Invoice Paid Status Control
authorSandra Huguet <sandra.huguet@openbravo.com>
Tue, 11 Feb 2014 12:19:57 +0100
changeset 21940 87765308f9bd
parent 21939 d15c74980654
child 21941 1a763d40447c
child 22066 06ab754c8414
Fixed issue 25696 Invoice Paid Status Control
modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml
modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_ISPAYMENTCONFIRMED.xml
modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_SEQNUMBERPAYMENTSTATUS.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_FIELD.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_VAL_RULE.xml
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/Reconciliation.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPayment.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_ExecutePayment.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentProcess.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_ReconciliationProcess.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_TransactionProcess.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java
src-db/database/model/tables/FIN_FINACC_PAYMENTMETHOD.xml
src-db/database/model/tables/FIN_PAYMENT_SCHEDULEDETAIL.xml
src-db/database/sourcedata/AD_COLUMN.xml
src-db/database/sourcedata/AD_ELEMENT.xml
src-db/database/sourcedata/AD_FIELD.xml
src-db/database/sourcedata/AD_REF_LIST.xml
src-util/modulescript/build/classes/org/openbravo/modulescript/InitializeIsPaymentPaid.class
src-util/modulescript/build/classes/org/openbravo/modulescript/InitializeIsPaymentPaidData.class
src-util/modulescript/src/org/openbravo/modulescript/InitializeIsPaymentPaid.java
src-util/modulescript/src/org/openbravo/modulescript/InitializeIsPaymentPaid_data.xsql
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_GEN_PAYMENTSCHEDULE_INV.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -81,6 +81,7 @@
 v_finacct_currency VARCHAR2(32);
 v_rate NUMBER;
 v_PricePr NUMBER;
+v_isinvoicepaid CHAR(1):= 'N';
 v_IsCashVAT C_Invoice.IsCashVAT%TYPE;
 
 TYPE RECORD IS REF CURSOR;
@@ -89,6 +90,8 @@
 cur_finaccpaymentmethod RECORD;
 cur_PaymentScheduleOrder RECORD;
 cur_linktopayment_scheddetails RECORD;
+cur_update_scheddetails RECORD;
+cur_invoicepaid RECORD;
 
 BEGIN
 
@@ -169,7 +172,8 @@
       END;
     END IF;
     -- END Extension Point
-
+    
+    
     DECLARE
       cur_payments RECORD;
       cur_order_schdet_ISOPEN BOOLEAN:=false;
@@ -203,7 +207,7 @@
              fin_payment_scheduledetail_id,
              fin_payment_scheduledetail.fin_payment_schedule_order,
              fin_payment_scheduledetail.fin_payment_detail_id,
-             CASE WHEN fin_payment.status IN ('PPM', 'RPR', 'PWNC', 'RDNC', 'RPPC') THEN 'Y' ELSE 'N' END AS paid,
+             fin_payment_scheduledetail.isinvoicepaid AS paid,
              CASE WHEN fin_payment_scheduledetail.fin_payment_detail_id is not null THEN 0 ELSE 1 END AS priority
       FROM c_invoiceline, c_orderline, fin_payment_schedule,
         fin_payment_scheduledetail LEFT JOIN fin_payment_detail ON fin_payment_scheduledetail.fin_payment_detail_id = fin_payment_detail.fin_payment_detail_id
@@ -242,7 +246,7 @@
             
       --Insert Payment Schedules for Invoices
       v_pendingAmount := v_GrandTotal - coalesce(v_ConsumedGranTotal, 0);
-      
+
       IF (v_pendingAmount <> 0) THEN
 
         --get number of payment schedules expected for the invoice
@@ -353,7 +357,7 @@
               v_scheduledetailamount := v_differenceamount;
               v_scheduledetailid := v_new_scheduledetailid;
             END IF;
-
+            
             IF (order_schdet.order_id <> v_oldorder) THEN
               -- get invoiced amount for the order
               SELECT COALESCE(SUM(c_invoiceline.linenetamt+c_getinvoiceline_taxamount(c_invoiceline.c_invoiceline_id)),0) INTO v_invoicedamount
@@ -477,8 +481,25 @@
                   updatedby = p_user
               WHERE fin_payment_scheduledetail_id = v_scheduledetailid;
 
+               UPDATE FIN_PAYMENT_SCHEDULEDETAIL
+              SET isinvoicepaid=(select CASE WHEN fpsd.fin_payment_detail_id is null then 'N'
+                  WHEN ((aprm_seqnumberpaymentstatus(fp.status))>= (aprm_seqnumberpaymentstatus((CASE WHEN fp.isreceipt='Y' 
+                  THEN Payin_Invoicepaidstatus ELSE Payout_Invoicepaidstatus END)))) THEN 'Y' ELSE 'N' END
+                  from fin_payment_scheduledetail fpsd
+                  left join fin_payment_detail fpd on fpsd.fin_payment_detail_id=fpd.fin_payment_detail_id
+                  left join fin_payment fp on fpd.fin_payment_id=fp.fin_payment_id
+                  left join fin_financial_account fa on fa.fin_financial_account_id=fp.fin_financial_account_id 
+                  left join FIN_FinAcc_PaymentMethod fpm on fpm.fin_financial_account_id=fp.fin_financial_account_id 
+                 and fpm.fin_paymentmethod_id=fp.fin_paymentmethod_id WHERE fin_payment_scheduledetail_id = v_scheduledetailid) 
+                 WHERE FIN_PAYMENT_SCHEDULEDETAIL_ID = v_scheduledetailid;
+              
               -- if paid, update paid and outstanding amount
-              IF (order_schdet.paid = 'Y') THEN
+              select isinvoicepaid 
+              into v_isinvoicepaid 
+              from fin_payment_scheduledetail
+              where fin_payment_scheduledetail_id = v_scheduledetailid;
+              
+              IF (v_isinvoicepaid = 'Y') THEN
                 UPDATE fin_payment_schedule
                 SET outstandingamt = outstandingamt - COALESCE(v_scheduledetailamount,0),
                     paidamt = paidamt + COALESCE(v_scheduledetailamount, 0)
@@ -543,7 +564,7 @@
         CLOSE cur_order_schdet;
       
       END IF;
-
+             
       -- Reading Data from FIN_PAYMENT_SCHEDULE
       SELECT COALESCE(sum(PAIDAMT),0) as PaidAmount, COALESCE(SUM(OUTSTANDINGAMT),0) as OutstandingAmount
         INTO v_PaidAmount,V_OutstandingAmount
@@ -725,8 +746,9 @@
                 'N', 'N', 'N', v_finpayment_desc,
                 v_Financial_Account_ID, v_PaymentDocType_ID, v_project_id, v_campaign_id, v_costcenter,
                 v_activity_id, v_user1, v_user2, 'N', 'N', 'N');
+
+              v_description_first := TRUE;
               
-              v_description_first := TRUE;
               -- link to the new payment all the pending payment schedule details
               FOR cur_linktopayment_scheddetails IN (
                    SELECT FIN_PAYMENT_SCHEDULEDETAIL_ID, AMOUNT
@@ -792,6 +814,27 @@
                   EM_APRM_PROCESS_PAYMENT = 'R'
               WHERE FIN_PAYMENT_ID = v_FIN_PAYMENT_ID;
 
+                           FOR cur_update_scheddetails IN (
+                SELECT fin_payment_scheduledetail_id
+                FROM fin_payment_schedule ps
+                INNER JOIN fin_payment_scheduledetail psd 
+                ON ps.fin_payment_schedule_id = psd.fin_payment_schedule_invoice                                                    
+                WHERE ps.c_invoice_id =p_record_id
+              )
+              LOOP
+              UPDATE FIN_PAYMENT_SCHEDULEDETAIL
+              SET isinvoicepaid=(select CASE WHEN fpsd.fin_payment_detail_id is null then 'N'
+                  WHEN ((aprm_seqnumberpaymentstatus(fp.status))>= (aprm_seqnumberpaymentstatus((CASE WHEN fp.isreceipt='Y' 
+                  THEN Payin_Invoicepaidstatus ELSE Payout_Invoicepaidstatus END)))) THEN 'Y' ELSE 'N' END
+                  from fin_payment_scheduledetail fpsd
+                  left join fin_payment_detail fpd on fpsd.fin_payment_detail_id=fpd.fin_payment_detail_id
+                  left join fin_payment fp on fpd.fin_payment_id=fp.fin_payment_id
+                  left join fin_financial_account fa on fa.fin_financial_account_id=fp.fin_financial_account_id 
+                  left join FIN_FinAcc_PaymentMethod fpm on fpm.fin_financial_account_id=fp.fin_financial_account_id 
+                 and fpm.fin_paymentmethod_id=fp.fin_paymentmethod_id WHERE fin_payment_scheduledetail_id = cur_update_scheddetails.fin_payment_scheduledetail_id) 
+                 WHERE FIN_PAYMENT_SCHEDULEDETAIL_ID = cur_update_scheddetails.fin_payment_scheduledetail_id;
+              END LOOP;
+
               -- Update payment schedule amounts and payment monitor in case that the payment is not left in awaiting
               -- execution status.
               FOR cur_PaymentScheduleOrder IN (
@@ -814,7 +857,8 @@
                     v_finpayment_desc:=v_finpayment_desc || ', ' || v_orderno;
                   END IF;
                 END IF;
-                IF (cur_finaccpaymentmethod.ExecutionType<>'A') THEN
+                
+                  IF (cur_finaccpaymentmethod.ExecutionType<>'A') THEN
                   UPDATE FIN_PAYMENT_SCHEDULE
                   SET PAIDAMT = (SELECT COALESCE(sum(amount + COALESCE(writeoffamt, 0)), 0)
                                  FROM fin_payment_scheduledetail
@@ -823,7 +867,8 @@
                                        exists (SELECT 1
                                                FROM fin_payment, fin_payment_detail
                                                WHERE fin_payment.fin_payment_id = fin_payment_detail.fin_payment_id
-                                                      and fin_payment.processed='Y' and fin_payment.status<>'RPAE'
+                                                      and fin_payment.processed='Y' 
+                                                      and fin_payment_scheduledetail.isinvoicepaid='Y'
                                                       and fin_payment_detail.fin_payment_detail_id = fin_payment_scheduledetail.fin_payment_detail_id)),
                       OUTSTANDINGAMT = (SELECT COALESCE(sum(amount), 0)
                                         FROM fin_payment_scheduledetail
@@ -832,8 +877,10 @@
                                        exists (SELECT 1
                                                FROM fin_payment, fin_payment_detail
                                                WHERE fin_payment.fin_payment_id = fin_payment_detail.fin_payment_id
-                                                      and fin_payment.processed='Y' and fin_payment.status = 'RPAE'
+                                                      and fin_payment.processed='Y' 
+                                                      and fin_payment_scheduledetail.isinvoicepaid='Y'
                                                       and fin_payment_detail.fin_payment_detail_id = fin_payment_scheduledetail.fin_payment_detail_id)))
+
                   WHERE FIN_PAYMENT_SCHEDULE_ID = cur_PaymentScheduleOrder.FIN_PAYMENT_SCHEDULE_ORDER;
                 END IF;
               END LOOP;
@@ -842,7 +889,17 @@
               END IF;
               UPDATE FIN_PAYMENT SET DESCRIPTION = v_finpayment_desc
                 WHERE FIN_PAYMENT_ID = v_FIN_PAYMENT_ID;
-              IF (cur_finaccpaymentmethod.ExecutionType<>'A') THEN  
+
+              FOR cur_invoicepaid IN (
+                select isinvoicepaid from fin_payment_scheduledetail fpsd
+               left join fin_payment_detail fpd on fpsd.fin_payment_detail_id=fpd.fin_payment_detail_id
+               left join fin_payment fp on fpd.fin_payment_id=fp.fin_payment_id
+               left join fin_payment_schedule ps ON ps.fin_payment_schedule_id = fpsd.fin_payment_schedule_invoice
+                 WHERE ps.c_invoice_id =p_record_id
+              )
+             LOOP
+
+              IF ((cur_finaccpaymentmethod.ExecutionType<>'A') AND (cur_invoicepaid.isinvoicepaid='Y')) THEN 
                 UPDATE FIN_PAYMENT_SCHEDULE
                 SET PAIDAMT = PAIDAMT + COALESCE(cur_paymentschedule.OUTSTANDINGAMT,0),
                     OUTSTANDINGAMT = OUTSTANDINGAMT - COALESCE(cur_paymentschedule.OUTSTANDINGAMT, 0)
@@ -870,7 +927,7 @@
                 SET SO_CREDITUSED = COALESCE(SO_CREDITUSED,0) - (COALESCE(cur_paymentschedule.OUTSTANDINGAMT, 0) * v_creditmultiplier)
                 WHERE C_BPARTNER_ID = v_BPartner_ID;
               END IF;
-
+            END LOOP;
               -- Automatic creation of financial transaction
               IF(cur_finaccpaymentmethod.CreateFinTransaction = 'Y' AND cur_finaccpaymentmethod.ExecutionType = 'M') THEN
                 v_ResultStr:='Generating FIN_FINACC_TRANSACTION';
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_ISPAYMENTCONFIRMED.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_ISPAYMENTCONFIRMED.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -19,7 +19,7 @@
 * under the License.
 * The Original Code is Openbravo ERP.
 * The Initial Developer of the Original Code is Openbravo SLU
-* All portions are Copyright (C) 2011-2012 Openbravo SLU
+* All portions are Copyright (C) 2011-2013 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
@@ -28,30 +28,46 @@
   v_module   VARCHAR2(32);
   v_dbprefix   VARCHAR2(7);
   v_isPaymentConfirmed CHAR(1) := 'N';
+  v_isinvoicepaid CHAR(1):= 'N';
+  v_referencelist VARCHAR2(32):='575BCB88A4694C27BC013DE9C73E6FE7';
   TYPE RECORD IS REF CURSOR;
   Cur_Dbprefix RECORD;
-
+  v_invoicepaidstatus  VARCHAR2(32);
 BEGIN
   -- Check if the status exists
   SELECT count(*) INTO v_count FROM DUAL
   WHERE EXISTS (SELECT 1 FROM ad_ref_list
-                WHERE ad_reference_id = '575BCB88A4694C27BC013DE9C73E6FE7'
+                WHERE ad_reference_id = v_referencelist
                       AND value = status);
 
   IF (v_count = 0) THEN
     RETURN 'N';
   END IF;
-  IF (status IN ('PPM', 'RPR', 'PWNC', 'RDNC', 'RPPC')) THEN
-    -- core final statuses
-    v_isPaymentConfirmed := 'Y';
-  ELSIF (status IN ('RPAP', 'RPAE', 'RPVOID')) THEN
-    -- core intermediate statuses
-    v_isPaymentConfirmed := 'N';
-  ELSE
+  select isinvoicepaid 
+  into v_isinvoicepaid
+  from fin_payment_scheduledetail 
+  where fin_payment_scheduledetail_id=fin_payment_scheduledetail_id;
+  
+  IF ((fin_payment_scheduledetail_id <> '') AND (fin_payment_scheduledetail_id is not null))THEN
+    IF(v_isinvoicepaid='Y')THEN
+     -- core intermediate statuses
+      v_isPaymentConfirmed := 'Y';
+    ELSE
+     -- core intermediate statuses
+      v_isPaymentConfirmed := 'N';
+    END IF;
+  ELSE 
+    IF(status IN ('PPM', 'RPR', 'PWNC', 'RDNC', 'RPPC'))THEN
+     -- core intermediate statuses
+      v_isPaymentConfirmed := 'Y';
+    ELSIF (status IN ('RPAP', 'RPAE', 'RPVOID')) THEN
+     -- core intermediate statuses
+      v_isPaymentConfirmed := 'N'; 
+    ELSE
     -- statuses implemented by other module
     SELECT ad_module_id INTO v_module
     FROM ad_ref_list
-    WHERE ad_reference_id = '575BCB88A4694C27BC013DE9C73E6FE7'
+    WHERE ad_reference_id = v_referencelist
       AND value = status;
 
     -- if the module defines a merge can have several dbprefix
@@ -74,7 +90,7 @@
       END;
     END LOOP;
   END IF;
-
+  END IF;
   RETURN v_isPaymentConfirmed;
 
 EXCEPTION
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/model/functions/APRM_SEQNUMBERPAYMENTSTATUS.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -0,0 +1,53 @@
+<?xml version="1.0"?>
+  <database name="FUNCTION APRM_SEQNUMBERPAYMENTSTATUS">
+    <function name="APRM_SEQNUMBERPAYMENTSTATUS" type="VARCHAR">
+      <parameter name="status" type="VARCHAR" mode="in">
+        <default/>
+      </parameter>
+      <body><![CDATA[/*************************************************************************
+* The contents of this file are subject to the Openbravo  Public  License
+* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+* Version 1.1  with a permitted attribution clause; you may not  use this
+* file except in compliance with the License. You  may  obtain  a copy of
+* the License at http://www.openbravo.com/legal/license.html
+* Software distributed under the License  is  distributed  on  an "AS IS"
+* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+* License for the specific  language  governing  rights  and  limitations
+* under the License.
+* The Original Code is Openbravo ERP.
+* The Initial Developer of the Original Code is Openbravo SLU
+* All portions are Copyright (C) 2013 Openbravo SLU
+* All Rights Reserved.
+* Contributor(s):  ______________________________________.
+************************************************************************/
+  v_seqno VARCHAR2(32);
+  v_count NUMBER;
+  v_referencelist VARCHAR2(32):='575BCB88A4694C27BC013DE9C73E6FE7';
+
+BEGIN
+  -- Check if the status exists
+  SELECT count(*) INTO v_count FROM DUAL
+  WHERE EXISTS (SELECT 1 FROM ad_ref_list
+                WHERE ad_reference_id = v_referencelist
+                      AND value = status);
+
+  IF (v_count = 0) THEN
+    RETURN 'N';
+  END IF;
+  
+  SELECT seqno 
+  INTO v_seqno
+  FROM ad_ref_list
+  WHERE ad_reference_id = v_referencelist
+  and value = status;
+
+  RETURN v_seqno;
+
+EXCEPTION
+WHEN OTHERS THEN
+  DBMS_OUTPUT.PUT_LINE('aprm_seqnumberpaymentstatus exception');
+  RAISE;
+END APRM_SEQNUMBERPAYMENTSTATUS
+]]></body>
+    </function>
+  </database>
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_FIELD.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_FIELD.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -18507,6 +18507,64 @@
 <!--E1A05CE9F3FF433888C60B2F059480EC-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
 <!--E1A05CE9F3FF433888C60B2F059480EC--></AD_FIELD>
 
+<!--E1C580C830810696E040007F0100225E--><AD_FIELD>
+<!--E1C580C830810696E040007F0100225E-->  <AD_FIELD_ID><![CDATA[E1C580C830810696E040007F0100225E]]></AD_FIELD_ID>
+<!--E1C580C830810696E040007F0100225E-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--E1C580C830810696E040007F0100225E-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--E1C580C830810696E040007F0100225E-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--E1C580C830810696E040007F0100225E-->  <NAME><![CDATA[Invoice Paid]]></NAME>
+<!--E1C580C830810696E040007F0100225E-->  <DESCRIPTION><![CDATA[A flag indicating whether this document type is consider paid or not.]]></DESCRIPTION>
+<!--E1C580C830810696E040007F0100225E-->  <HELP><![CDATA[A flag indicating whether this document type is consider paid or not.]]></HELP>
+<!--E1C580C830810696E040007F0100225E-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--E1C580C830810696E040007F0100225E-->  <AD_TAB_ID><![CDATA[F6C2283A21314407BBBB23FF14B85ED4]]></AD_TAB_ID>
+<!--E1C580C830810696E040007F0100225E-->  <AD_COLUMN_ID><![CDATA[C5CABD48EA774B8289401E670504371C]]></AD_COLUMN_ID>
+<!--E1C580C830810696E040007F0100225E-->  <IGNOREINWAD><![CDATA[N]]></IGNOREINWAD>
+<!--E1C580C830810696E040007F0100225E-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
+<!--E1C580C830810696E040007F0100225E-->  <DISPLAYLOGIC><![CDATA[@InvoicePaidStatus@='Y']]></DISPLAYLOGIC>
+<!--E1C580C830810696E040007F0100225E-->  <DISPLAYLENGTH><![CDATA[1]]></DISPLAYLENGTH>
+<!--E1C580C830810696E040007F0100225E-->  <ISREADONLY><![CDATA[Y]]></ISREADONLY>
+<!--E1C580C830810696E040007F0100225E-->  <SEQNO><![CDATA[280]]></SEQNO>
+<!--E1C580C830810696E040007F0100225E-->  <ISSAMELINE><![CDATA[N]]></ISSAMELINE>
+<!--E1C580C830810696E040007F0100225E-->  <ISFIELDONLY><![CDATA[N]]></ISFIELDONLY>
+<!--E1C580C830810696E040007F0100225E-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--E1C580C830810696E040007F0100225E-->  <SHOWINRELATION><![CDATA[N]]></SHOWINRELATION>
+<!--E1C580C830810696E040007F0100225E-->  <ISFIRSTFOCUSEDFIELD><![CDATA[N]]></ISFIRSTFOCUSEDFIELD>
+<!--E1C580C830810696E040007F0100225E-->  <AD_MODULE_ID><![CDATA[A918E3331C404B889D69AA9BFAFB23AC]]></AD_MODULE_ID>
+<!--E1C580C830810696E040007F0100225E-->  <STARTINODDCOLUMN><![CDATA[N]]></STARTINODDCOLUMN>
+<!--E1C580C830810696E040007F0100225E-->  <STARTNEWLINE><![CDATA[N]]></STARTNEWLINE>
+<!--E1C580C830810696E040007F0100225E-->  <ISSHOWNINSTATUSBAR><![CDATA[N]]></ISSHOWNINSTATUSBAR>
+<!--E1C580C830810696E040007F0100225E-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
+<!--E1C580C830810696E040007F0100225E--></AD_FIELD>
+
+<!--E215E9D7AE7B4C12E040007F01001D97--><AD_FIELD>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <AD_FIELD_ID><![CDATA[E215E9D7AE7B4C12E040007F01001D97]]></AD_FIELD_ID>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <NAME><![CDATA[Invoice Paid]]></NAME>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <DESCRIPTION><![CDATA[A flag indicating whether this document type is consider paid or not.]]></DESCRIPTION>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <HELP><![CDATA[A flag indicating whether this document type is consider paid or not.]]></HELP>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <AD_TAB_ID><![CDATA[9817E22E2536417F8C9AEC8D5FA33E18]]></AD_TAB_ID>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <AD_COLUMN_ID><![CDATA[C5CABD48EA774B8289401E670504371C]]></AD_COLUMN_ID>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <IGNOREINWAD><![CDATA[N]]></IGNOREINWAD>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <DISPLAYLOGIC><![CDATA[@InvoicePaidStatus@='Y']]></DISPLAYLOGIC>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <DISPLAYLENGTH><![CDATA[1]]></DISPLAYLENGTH>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISREADONLY><![CDATA[N]]></ISREADONLY>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <SEQNO><![CDATA[240]]></SEQNO>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISSAMELINE><![CDATA[N]]></ISSAMELINE>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISFIELDONLY><![CDATA[N]]></ISFIELDONLY>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <SHOWINRELATION><![CDATA[N]]></SHOWINRELATION>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISFIRSTFOCUSEDFIELD><![CDATA[N]]></ISFIRSTFOCUSEDFIELD>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <AD_MODULE_ID><![CDATA[A918E3331C404B889D69AA9BFAFB23AC]]></AD_MODULE_ID>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <STARTINODDCOLUMN><![CDATA[N]]></STARTINODDCOLUMN>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <STARTNEWLINE><![CDATA[N]]></STARTNEWLINE>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <ISSHOWNINSTATUSBAR><![CDATA[N]]></ISSHOWNINSTATUSBAR>
+<!--E215E9D7AE7B4C12E040007F01001D97-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
+<!--E215E9D7AE7B4C12E040007F01001D97--></AD_FIELD>
+
 <!--E452E6D8D7D14E56BFD0D9EFD22C2B4A--><AD_FIELD>
 <!--E452E6D8D7D14E56BFD0D9EFD22C2B4A-->  <AD_FIELD_ID><![CDATA[E452E6D8D7D14E56BFD0D9EFD22C2B4A]]></AD_FIELD_ID>
 <!--E452E6D8D7D14E56BFD0D9EFD22C2B4A-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_VAL_RULE.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_VAL_RULE.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -11,6 +11,28 @@
 <!--119E4BFBC4264A148450053A47E7D3FE-->  <AD_MODULE_ID><![CDATA[A918E3331C404B889D69AA9BFAFB23AC]]></AD_MODULE_ID>
 <!--119E4BFBC4264A148450053A47E7D3FE--></AD_VAL_RULE>
 
+<!--1D824F88E32F4282B26C48B5A910B006--><AD_VAL_RULE>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <AD_VAL_RULE_ID><![CDATA[1D824F88E32F4282B26C48B5A910B006]]></AD_VAL_RULE_ID>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <NAME><![CDATA[FIN_Payment Out status validation]]></NAME>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <TYPE><![CDATA[S]]></TYPE>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <CODE><![CDATA[Value not IN ('RPR','RDNC') and seqno >=(select seqno FROM ad_ref_list WHERE ad_reference_id = '575BCB88A4694C27BC013DE9C73E6FE7' and value='PPM')]]></CODE>
+<!--1D824F88E32F4282B26C48B5A910B006-->  <AD_MODULE_ID><![CDATA[A918E3331C404B889D69AA9BFAFB23AC]]></AD_MODULE_ID>
+<!--1D824F88E32F4282B26C48B5A910B006--></AD_VAL_RULE>
+
+<!--27D8D0FDAE4742229DC64888DF9CB8A8--><AD_VAL_RULE>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <AD_VAL_RULE_ID><![CDATA[27D8D0FDAE4742229DC64888DF9CB8A8]]></AD_VAL_RULE_ID>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <NAME><![CDATA[FIN_Payment In status validation]]></NAME>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <TYPE><![CDATA[S]]></TYPE>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <CODE><![CDATA[Value not IN  ('PPM','PWNC') and seqno >=(select seqno FROM ad_ref_list WHERE ad_reference_id = '575BCB88A4694C27BC013DE9C73E6FE7' and value='RPR')]]></CODE>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8-->  <AD_MODULE_ID><![CDATA[A918E3331C404B889D69AA9BFAFB23AC]]></AD_MODULE_ID>
+<!--27D8D0FDAE4742229DC64888DF9CB8A8--></AD_VAL_RULE>
+
 <!--29010995FD39439D97A5C0CE8CE27D70--><AD_VAL_RULE>
 <!--29010995FD39439D97A5C0CE8CE27D70-->  <AD_VAL_RULE_ID><![CDATA[29010995FD39439D97A5C0CE8CE27D70]]></AD_VAL_RULE_ID>
 <!--29010995FD39439D97A5C0CE8CE27D70-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/Reconciliation.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/Reconciliation.java	Tue Feb 11 12:19:57 2014 +0100
@@ -55,6 +55,8 @@
 import org.openbravo.model.common.enterprise.DocumentType;
 import org.openbravo.model.financialmgmt.payment.FIN_FinaccTransaction;
 import org.openbravo.model.financialmgmt.payment.FIN_FinancialAccount;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentDetail;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
 import org.openbravo.model.financialmgmt.payment.FIN_Reconciliation;
 import org.openbravo.model.financialmgmt.payment.FIN_ReconciliationLine_v;
 import org.openbravo.xmlEngine.XmlDocument;
@@ -293,6 +295,23 @@
             // Changing dates for accounting entries as well
             TransactionsDao.updateAccountingDate(trans);
           }
+          Boolean invoicePaidold = false;
+          for (FIN_PaymentDetail pd : finacctrxv.getPayment().getFINPaymentDetailList()) {
+            for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+              invoicePaidold = psd.isInvoicePaid();
+              if (!invoicePaidold) {
+                if ((FIN_Utility.invoicePaymentStatus(finacctrxv.getPayment().getPaymentMethod(),
+                    reconciliation.getAccount(), finacctrxv.getPayment().isReceipt())
+                    .equals(finacctrxv.getPayment().getStatus()))) {
+                  psd.setInvoicePaid(true);
+                }
+                if (psd.isInvoicePaid()) {
+                  FIN_Utility.updatePaymentAmounts(psd);
+                }
+              }
+            }
+            FIN_Utility.updateBusinessPartnerCredit(finacctrxv.getPayment());
+          }
         }
 
         reconciliation.setDocumentStatus("CO");
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Tue Feb 11 12:19:57 2014 +0100
@@ -1912,14 +1912,12 @@
   public List<FIN_Payment> getCustomerPaymentsWithCredit(Organization org, BusinessPartner bp,
       boolean isReceipt) {
 
-    List<String> confirmedStatus = FIN_Utility.getListPaymentConfirmed();
     try {
       OBContext.setAdminMode(true);
       OBCriteria<FIN_Payment> obcPayment = OBDal.getInstance().createCriteria(FIN_Payment.class);
       obcPayment.add(Restrictions.eq(FIN_Payment.PROPERTY_BUSINESSPARTNER, bp));
       obcPayment.add(Restrictions.eq(FIN_Payment.PROPERTY_RECEIPT, isReceipt));
       obcPayment.add(Restrictions.ne(FIN_Payment.PROPERTY_GENERATEDCREDIT, BigDecimal.ZERO));
-      obcPayment.add(Restrictions.in(FIN_Payment.PROPERTY_STATUS, confirmedStatus));
       obcPayment.add(Restrictions.neProperty(FIN_Payment.PROPERTY_GENERATEDCREDIT,
           FIN_Payment.PROPERTY_USEDCREDIT));
       final Organization legalEntity = FIN_Utility.getLegalEntityOrg(org);
@@ -1928,7 +1926,17 @@
       obcPayment.add(Restrictions.in("organization.id", orgIds));
       obcPayment.addOrderBy(FIN_Payment.PROPERTY_PAYMENTDATE, true);
       obcPayment.addOrderBy(FIN_Payment.PROPERTY_DOCUMENTNO, true);
-      return obcPayment.list();
+      List<FIN_Payment> paymentList = new ArrayList<FIN_Payment>();
+      for (FIN_Payment fp : obcPayment.list()) {
+        for (FIN_PaymentDetail fpd : fp.getFINPaymentDetailList()) {
+          for (FIN_PaymentScheduleDetail fpsd : fpd.getFINPaymentScheduleDetailList()) {
+            if (fpsd.isInvoicePaid()) {
+              paymentList.add(fp);
+            }
+          }
+        }
+      }
+      return paymentList;
     } finally {
       OBContext.restorePreviousMode();
     }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPayment.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPayment.java	Tue Feb 11 12:19:57 2014 +0100
@@ -1208,10 +1208,8 @@
       Date paymentDueDate = paymentSchedule.getDueDate();
       for (FIN_PaymentScheduleDetail psd : paymentSchedule
           .getFINPaymentScheduleDetailInvoicePaymentScheduleList()) {
-        if (!psd.isCanceled()
-            && psd.getPaymentDetails() != null
-            && (FIN_Utility.isPaymentConfirmed(psd.getPaymentDetails().getFinPayment().getStatus(),
-                psd) || currentPSD.getId().equals(psd.getId()))) {
+        if (!psd.isCanceled() && psd.getPaymentDetails() != null
+            && (psd.isInvoicePaid() || currentPSD.getId().equals(psd.getId()))) {
           Date paymentDate = psd.getPaymentDetails().getFinPayment().getPaymentDate();
           if (paymentDate.after(paymentDueDate)) {
             overdueOriginal = overdueOriginal.add(psd.getAmount());
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_ExecutePayment.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_ExecutePayment.java	Tue Feb 11 12:19:57 2014 +0100
@@ -163,7 +163,15 @@
               dao.removeFromExecutionPending(paymentRunPayment.getPayment());
           }
 
-          String paymentStatus = paymentRunPayment.getPayment().getStatus();
+          FIN_Payment payment = paymentRunPayment.getPayment();
+          if ((FIN_Utility.invoicePaymentStatus(payment).equals(payment.getStatus()))) {
+            for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
+              for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+                psd.setInvoicePaid(true);
+              }
+            }
+          }
+
           if ("S".equals(paymentRunPayment.getResult())) {
             if ("PPW".equals(paymentRun.getSourceOfTheExecution())) {
               FIN_PaymentProposal pp = getPaymentProposalFromPayment(paymentRunPayment.getPayment());
@@ -172,27 +180,41 @@
               OBDal.getInstance().flush();
             }
             paymentRunPayment.getPayment().setPosted("N");
-            if (("RPR".equals(paymentStatus) || "PPM".equals(paymentStatus))
-                && FIN_Utility.isAutomaticDepositWithdrawn(paymentRunPayment.getPayment())
-                && paymentRunPayment.getPayment().getAmount().compareTo(BigDecimal.ZERO) != 0) {
-              FIN_FinaccTransaction transaction = TransactionsDao
-                  .createFinAccTransaction(paymentRunPayment.getPayment());
-              // VariablesSecureApp vars = new VariablesSecureApp(OBContext.getOBContext().getUser()
-              // .getId(), OBContext.getOBContext().getCurrentOrganization().getId(), OBContext
-              // .getOBContext().getRole().getId());
-              VariablesSecureApp vars = new VariablesSecureApp(RequestContext.get().getRequest());
-              OBError processTransactionError = processTransaction(vars,
-                  new DalConnectionProvider(), "P", transaction);
-              if (processTransactionError != null
-                  && "Error".equals(processTransactionError.getType())) {
-                return processTransactionError;
+            try {
+              for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
+                for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+                  if (psd.isInvoicePaid()
+                      && FIN_Utility.isAutomaticDepositWithdrawn(paymentRunPayment.getPayment())
+                      && paymentRunPayment.getPayment().getAmount().compareTo(BigDecimal.ZERO) != 0) {
+                    FIN_FinaccTransaction transaction = TransactionsDao
+                        .createFinAccTransaction(paymentRunPayment.getPayment());
+                    VariablesSecureApp vars = new VariablesSecureApp(RequestContext.get()
+                        .getRequest());
+                    OBError processTransactionError = processTransaction(vars,
+                        new DalConnectionProvider(), "P", transaction);
+                    if (processTransactionError != null
+                        && "Error".equals(processTransactionError.getType())) {
+                      return processTransactionError;
+                    }
+                  }
+                }
+              }
+
+            } finally {
+              OBContext.restorePreviousMode();
+            }
+          }
+          try {
+            OBContext.setAdminMode(true);
+            for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
+              for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+                if (psd.isInvoicePaid()) {
+                  updatePaymentAmounts(paymentRunPayment.getPayment());
+                }
               }
             }
-          }
-          if ("PPM".equals(paymentStatus) || "RPR".equals(paymentStatus)
-              || "PWNC".equals(paymentStatus) || "RDNC".equals(paymentStatus)
-              || "RPPC".equals(paymentStatus)) {
-            updatePaymentAmounts(paymentRunPayment.getPayment());
+          } finally {
+            OBContext.restorePreviousMode();
           }
           OBDal.getInstance().save(paymentRunPayment.getPayment());
 
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentProcess.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_PaymentProcess.java	Tue Feb 11 12:19:57 2014 +0100
@@ -379,40 +379,53 @@
               for (FIN_PaymentScheduleDetail paymentScheduleDetail : obcPSD.list()) {
                 BigDecimal amount = paymentScheduleDetail.getAmount().add(
                     paymentScheduleDetail.getWriteoffAmount());
-                if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
-                  // BP SO_CreditUsed
-                  businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule().getInvoice()
-                      .getBusinessPartner();
-                  // Payments update credit opposite to invoices
-                  if (isReceipt) {
-                    decreaseCustomerCredit(businessPartner, amount);
-                  } else {
-                    increaseCustomerCredit(businessPartner, amount);
+                // Do not restore paid amounts if the payment is awaiting execution.
+                boolean invoicePaidAmounts = (FIN_Utility.seqnumberpaymentstatus(isReceipt ? "RPR"
+                    : "PPM")) >= (FIN_Utility.seqnumberpaymentstatus(FIN_Utility
+                    .invoicePaymentStatus(payment)));
+                paymentScheduleDetail.setInvoicePaid(false);
+                if (invoicePaidAmounts) {
+                  if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
+                    // BP SO_CreditUsed
+                    businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule()
+                        .getInvoice().getBusinessPartner();
+
+                    // Payments update credit opposite to invoices
+                    if (isReceipt) {
+                      decreaseCustomerCredit(businessPartner, amount);
+                    } else {
+                      increaseCustomerCredit(businessPartner, amount);
+                    }
+                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
+                        paymentScheduleDetail.getInvoicePaymentSchedule(),
+                        paymentScheduleDetail.getAmount(),
+                        paymentScheduleDetail.getWriteoffAmount());
+                    paymentScheduleDetail.setInvoicePaid(true);
                   }
-                  FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
-                      paymentScheduleDetail.getInvoicePaymentSchedule(),
-                      paymentScheduleDetail.getAmount(), paymentScheduleDetail.getWriteoffAmount());
-                }
-                if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
-                  FIN_AddPayment.updatePaymentScheduleAmounts(
-                      paymentScheduleDetail.getOrderPaymentSchedule(),
-                      paymentScheduleDetail.getAmount(), paymentScheduleDetail.getWriteoffAmount());
-                }
-                // when generating credit for a BP SO_CreditUsed is also updated
-                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
-                    && paymentScheduleDetail.getOrderPaymentSchedule() == null
-                    && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
-                    && !paymentDetail.isRefund()) {
-                  // BP SO_CreditUsed
-                  if (isReceipt) {
-                    decreaseCustomerCredit(businessPartner, amount);
-                  } else {
-                    increaseCustomerCredit(businessPartner, amount);
+
+                  if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
+                    FIN_AddPayment.updatePaymentScheduleAmounts(
+                        paymentScheduleDetail.getOrderPaymentSchedule(),
+                        paymentScheduleDetail.getAmount(),
+                        paymentScheduleDetail.getWriteoffAmount());
+                  }
+                  // when generating credit for a BP SO_CreditUsed is also updated
+                  if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
+                      && paymentScheduleDetail.getOrderPaymentSchedule() == null
+                      && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
+                      && !paymentDetail.isRefund()) {
+                    // BP SO_CreditUsed
+                    if (isReceipt) {
+                      decreaseCustomerCredit(businessPartner, amount);
+                    } else {
+                      increaseCustomerCredit(businessPartner, amount);
+                    }
                   }
                 }
               }
             }
             payment.setStatus(isReceipt ? "RPR" : "PPM");
+
             if ((strAction.equals("D") || FIN_Utility.isAutomaticDepositWithdrawn(payment))
                 && payment.getAmount().compareTo(BigDecimal.ZERO) != 0)
               triggerAutomaticFinancialAccountTransaction(vars, conProvider, payment);
@@ -523,6 +536,7 @@
                   OBDal.getInstance().save(openPSD);
                 }
               }
+
               FIN_PaymentScheduleDetail reversedPaymentSchedDetail = (FIN_PaymentScheduleDetail) DalUtil
                   .copy(psd, false);
               reversedPaymentSchedDetail.setPaymentDetails(reversedPaymentDetail);
@@ -531,7 +545,18 @@
               reversedPaymentSchedDetail.setAmount(psd.getAmount().negate());
               OBDal.getInstance().save(reversedPaymentSchedDetail);
               reversedSchedDetails.add(reversedPaymentSchedDetail);
+
+              if ((FIN_Utility.invoicePaymentStatus(reversedPayment).equals(reversedPayment
+                  .getStatus()))) {
+                reversedPaymentSchedDetail.setInvoicePaid(true);
+
+              } else {
+                reversedPaymentSchedDetail.setInvoicePaid(false);
+              }
+              OBDal.getInstance().save(reversedPaymentSchedDetail);
+
             }
+
             reversedPaymentDetail.setFINPaymentScheduleDetailList(reversedSchedDetails);
             OBDal.getInstance().save(reversedPaymentDetail);
             reversedDetails.add(reversedPaymentDetail);
@@ -653,7 +678,8 @@
         }
 
         // Do not restore paid amounts if the payment is awaiting execution.
-        boolean restorePaidAmounts = !"RPAE".equals(payment.getStatus());
+        boolean restorePaidAmounts = (FIN_Utility.seqnumberpaymentstatus(payment.getStatus())) <= (FIN_Utility
+            .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
         // Initialize amounts
         payment.setProcessed(false);
         OBDal.getInstance().save(payment);
@@ -705,176 +731,204 @@
             removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
             for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                 .getFINPaymentScheduleDetailList()) {
-              BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount();
-              BigDecimal psdAmount = paymentScheduleDetail.getAmount();
-              BigDecimal amount = psdAmount.add(psdWriteoffAmount);
-              if (psdWriteoffAmount.signum() != 0 && strAction.equals("RE")) {
-                // Restore write off
-                List<FIN_PaymentScheduleDetail> outstandingPDSs = FIN_AddPayment
-                    .getOutstandingPSDs(paymentScheduleDetail);
-                BigDecimal outstandingDebtAmount = BigDecimal.ZERO;
-                if (outstandingPDSs.size() > 0) {
-                  outstandingPDSs.get(0).setAmount(
-                      outstandingPDSs.get(0).getAmount().add(psdWriteoffAmount));
-                  OBDal.getInstance().save(outstandingPDSs.get(0));
-                } else {
-                  FIN_PaymentScheduleDetail outstandingPSD = (FIN_PaymentScheduleDetail) DalUtil
-                      .copy(paymentScheduleDetail, false);
-                  outstandingPSD.setAmount(psdWriteoffAmount);
-                  if (paymentScheduleDetail.getDoubtfulDebtAmount().signum() != 0) {
-                    if (psdWriteoffAmount.compareTo(paymentScheduleDetail.getDoubtfulDebtAmount()) >= 0) {
-                      outstandingDebtAmount = paymentScheduleDetail.getDoubtfulDebtAmount();
-                    } else {
-                      outstandingDebtAmount = psdWriteoffAmount;
+              Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid();
+              if (invoicePaidold) {
+                BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount();
+                BigDecimal psdAmount = paymentScheduleDetail.getAmount();
+                BigDecimal amount = psdAmount.add(psdWriteoffAmount);
+                if (psdWriteoffAmount.signum() != 0 && strAction.equals("RE")) {
+                  // Restore write off
+                  List<FIN_PaymentScheduleDetail> outstandingPDSs = FIN_AddPayment
+                      .getOutstandingPSDs(paymentScheduleDetail);
+                  BigDecimal outstandingDebtAmount = BigDecimal.ZERO;
+                  if (outstandingPDSs.size() > 0) {
+                    outstandingPDSs.get(0).setAmount(
+                        outstandingPDSs.get(0).getAmount().add(psdWriteoffAmount));
+                    OBDal.getInstance().save(outstandingPDSs.get(0));
+                  } else {
+                    FIN_PaymentScheduleDetail outstandingPSD = (FIN_PaymentScheduleDetail) DalUtil
+                        .copy(paymentScheduleDetail, false);
+                    outstandingPSD.setAmount(psdWriteoffAmount);
+                    if (paymentScheduleDetail.getDoubtfulDebtAmount().signum() != 0) {
+                      if (psdWriteoffAmount
+                          .compareTo(paymentScheduleDetail.getDoubtfulDebtAmount()) >= 0) {
+                        outstandingDebtAmount = paymentScheduleDetail.getDoubtfulDebtAmount();
+                      } else {
+                        outstandingDebtAmount = psdWriteoffAmount;
+                      }
+                    }
+                    outstandingPSD.setDoubtfulDebtAmount(outstandingDebtAmount);
+                    outstandingPSD.setWriteoffAmount(BigDecimal.ZERO);
+                    outstandingPSD.setPaymentDetails(null);
+                    OBDal.getInstance().save(outstandingPSD);
+                  }
+                  paymentScheduleDetail.setWriteoffAmount(BigDecimal.ZERO);
+                  paymentScheduleDetail.setDoubtfulDebtAmount(paymentScheduleDetail
+                      .getDoubtfulDebtAmount().subtract(outstandingDebtAmount));
+                  paymentScheduleDetail.getPaymentDetails().setWriteoffAmount(BigDecimal.ZERO);
+                  OBDal.getInstance().save(paymentScheduleDetail.getPaymentDetails());
+                  OBDal.getInstance().save(paymentScheduleDetail);
+                }
+                if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
+                  // Remove invoice description related to the credit payments
+                  final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule()
+                      .getInvoice();
+                  invoiceDocNos.add(invoice.getDocumentNo());
+                  final String invDesc = invoice.getDescription();
+                  if (invDesc != null) {
+                    final String creditMsg = Utility.messageBD(new DalConnectionProvider(),
+                        "APRM_InvoiceDescUsedCredit", vars.getLanguage());
+                    if (creditMsg != null) {
+                      StringBuffer newDesc = new StringBuffer();
+                      for (final String line : invDesc.split("\n")) {
+                        if (!line.startsWith(creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) {
+                          newDesc.append(line);
+                          if (!"".equals(line))
+                            newDesc.append("\n");
+                        }
+                      }
+                      if (newDesc.length() > 255) {
+                        newDesc = newDesc.delete(251, newDesc.length());
+                        newDesc = newDesc.append("...\n");
+                      }
+                      invoice.setDescription(newDesc.toString());
+
                     }
                   }
-                  outstandingPSD.setDoubtfulDebtAmount(outstandingDebtAmount);
-                  outstandingPSD.setWriteoffAmount(BigDecimal.ZERO);
-                  outstandingPSD.setPaymentDetails(null);
-                  OBDal.getInstance().save(outstandingPSD);
-                }
-                paymentScheduleDetail.setWriteoffAmount(BigDecimal.ZERO);
-                paymentScheduleDetail.setDoubtfulDebtAmount(paymentScheduleDetail
-                    .getDoubtfulDebtAmount().subtract(outstandingDebtAmount));
-                paymentScheduleDetail.getPaymentDetails().setWriteoffAmount(BigDecimal.ZERO);
-                OBDal.getInstance().save(paymentScheduleDetail.getPaymentDetails());
-                OBDal.getInstance().save(paymentScheduleDetail);
-              }
-              if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
-                // Remove invoice description related to the credit payments
-                final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule()
-                    .getInvoice();
-                invoiceDocNos.add(invoice.getDocumentNo());
-                final String invDesc = invoice.getDescription();
-                if (invDesc != null) {
-                  final String creditMsg = Utility.messageBD(new DalConnectionProvider(),
-                      "APRM_InvoiceDescUsedCredit", vars.getLanguage());
-                  if (creditMsg != null) {
-                    StringBuffer newDesc = new StringBuffer();
-                    for (final String line : invDesc.split("\n")) {
-                      if (!line.startsWith(creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) {
-                        newDesc.append(line);
-                        if (!"".equals(line))
-                          newDesc.append("\n");
-                      }
+                  if (restorePaidAmounts) {
+                    FIN_AddPayment.updatePaymentScheduleAmounts(
+                        paymentScheduleDetail.getInvoicePaymentSchedule(), psdAmount.negate(),
+                        psdWriteoffAmount.negate());
+                    paymentScheduleDetail.setInvoicePaid(false);
+                    OBDal.getInstance().save(paymentScheduleDetail);
+                    // BP SO_CreditUsed
+                    businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule()
+                        .getInvoice().getBusinessPartner();
+                    if (isReceipt) {
+                      increaseCustomerCredit(businessPartner, amount);
+                    } else {
+                      decreaseCustomerCredit(businessPartner, amount);
+
                     }
-                    if (newDesc.length() > 255) {
-                      newDesc = newDesc.delete(251, newDesc.length());
-                      newDesc = newDesc.append("...\n");
-                    }
-                    invoice.setDescription(newDesc.toString());
+
                   }
                 }
-                if (restorePaidAmounts) {
+                if (paymentScheduleDetail.getOrderPaymentSchedule() != null && restorePaidAmounts) {
                   FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
-                      paymentScheduleDetail.getInvoicePaymentSchedule(), psdAmount.negate(),
+                      paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(),
                       psdWriteoffAmount.negate());
+                }
+
+                // when generating credit for a BP SO_CreditUsed is also updated
+                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
+                    && paymentScheduleDetail.getOrderPaymentSchedule() == null
+                    && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
+                    && restorePaidAmounts && !paymentDetail.isRefund()) {
                   // BP SO_CreditUsed
-                  businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule().getInvoice()
-                      .getBusinessPartner();
                   if (isReceipt) {
                     increaseCustomerCredit(businessPartner, amount);
                   } else {
                     decreaseCustomerCredit(businessPartner, amount);
                   }
                 }
-              }
-              if (paymentScheduleDetail.getOrderPaymentSchedule() != null && restorePaidAmounts) {
-                FIN_AddPayment.updatePaymentScheduleAmounts(
-                    paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(),
-                    psdWriteoffAmount.negate());
-              }
-              // when generating credit for a BP SO_CreditUsed is also updated
-              if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
-                  && paymentScheduleDetail.getOrderPaymentSchedule() == null
-                  && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
-                  && restorePaidAmounts && !paymentDetail.isRefund()) {
-                // BP SO_CreditUsed
-                if (isReceipt) {
-                  increaseCustomerCredit(businessPartner, amount);
-                } else {
-                  decreaseCustomerCredit(businessPartner, amount);
+
+                if (paymentScheduleDetail.getOrderPaymentSchedule() != null && restorePaidAmounts) {
+                  FIN_AddPayment.updatePaymentScheduleAmounts(
+                      paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(),
+                      psdWriteoffAmount.negate());
+                }
+                // when generating credit for a BP SO_CreditUsed is also updated
+                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
+                    && paymentScheduleDetail.getOrderPaymentSchedule() == null
+                    && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
+                    && restorePaidAmounts && !paymentDetail.isRefund()) {
+                  // BP SO_CreditUsed
+                  if (isReceipt) {
+                    increaseCustomerCredit(businessPartner, amount);
+                  } else {
+                    decreaseCustomerCredit(businessPartner, amount);
+                  }
+                }
+                if (strAction.equals("R")
+                    || (strAction.equals("RE")
+                        && paymentScheduleDetail.getInvoicePaymentSchedule() == null
+                        && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail
+                        .getPaymentDetails().getGLItem() == null)) {
+                  FIN_AddPayment.mergePaymentScheduleDetails(paymentScheduleDetail);
+                  removedPDS.add(paymentScheduleDetail);
                 }
               }
-              if (strAction.equals("R")
-                  || (strAction.equals("RE")
-                      && paymentScheduleDetail.getInvoicePaymentSchedule() == null
-                      && paymentScheduleDetail.getOrderPaymentSchedule() == null && paymentScheduleDetail
-                      .getPaymentDetails().getGLItem() == null)) {
-                FIN_AddPayment.mergePaymentScheduleDetails(paymentScheduleDetail);
-                removedPDS.add(paymentScheduleDetail);
+              paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS);
+              if (strAction.equals("R")) {
+                OBDal.getInstance().getSession().refresh(paymentDetail);
               }
+              // If there is any schedule detail with amount zero, those are deleted
+              for (FIN_PaymentScheduleDetail psd : removedPDS) {
+                if (BigDecimal.ZERO.compareTo(psd.getAmount()) == 0
+                    && BigDecimal.ZERO.compareTo(psd.getWriteoffAmount()) == 0) {
+                  paymentDetail.getFINPaymentScheduleDetailList().remove(psd);
+                  OBDal.getInstance().getSession().refresh(paymentDetail);
+                  psd.getInvoicePaymentSchedule()
+                      .getFINPaymentScheduleDetailInvoicePaymentScheduleList().remove(psd);
+                  psd.getOrderPaymentSchedule()
+                      .getFINPaymentScheduleDetailOrderPaymentScheduleList().remove(psd);
+                  OBDal.getInstance().remove(psd);
+                }
+              }
+              if (paymentDetail.getFINPaymentScheduleDetailList().size() == 0) {
+                removedPD.add(paymentDetail);
+                removedPDIds.add(paymentDetail.getId());
+              }
+              OBDal.getInstance().save(paymentDetail);
             }
-            paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS);
+            for (String pdToRm : removedPDIds) {
+              OBDal.getInstance().remove(OBDal.getInstance().get(FIN_PaymentDetail.class, pdToRm));
+            }
+            payment.getFINPaymentDetailList().removeAll(removedPD);
             if (strAction.equals("R")) {
-              OBDal.getInstance().getSession().refresh(paymentDetail);
+              payment.getCurrencyConversionRateDocList().removeAll(conversionRates);
+              payment.setFinancialTransactionConvertRate(BigDecimal.ZERO);
             }
-            // If there is any schedule detail with amount zero, those are deleted
-            for (FIN_PaymentScheduleDetail psd : removedPDS) {
-              if (BigDecimal.ZERO.compareTo(psd.getAmount()) == 0
-                  && BigDecimal.ZERO.compareTo(psd.getWriteoffAmount()) == 0) {
-                paymentDetail.getFINPaymentScheduleDetailList().remove(psd);
-                OBDal.getInstance().getSession().refresh(paymentDetail);
-                psd.getInvoicePaymentSchedule()
-                    .getFINPaymentScheduleDetailInvoicePaymentScheduleList().remove(psd);
-                psd.getOrderPaymentSchedule().getFINPaymentScheduleDetailOrderPaymentScheduleList()
-                    .remove(psd);
-                OBDal.getInstance().remove(psd);
-              }
+            OBDal.getInstance().save(payment);
+
+            if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
+                && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
+              undoUsedCredit(payment, vars, invoiceDocNos);
             }
-            if (paymentDetail.getFINPaymentScheduleDetailList().size() == 0) {
-              removedPD.add(paymentDetail);
-              removedPDIds.add(paymentDetail.getId());
+
+            List<FIN_Payment> creditPayments = new ArrayList<FIN_Payment>();
+            for (final FIN_Payment_Credit pc : payment.getFINPaymentCreditList()) {
+              creditPayments.add(pc.getCreditPaymentUsed());
             }
-            OBDal.getInstance().save(paymentDetail);
-          }
-          for (String pdToRm : removedPDIds) {
-            OBDal.getInstance().remove(OBDal.getInstance().get(FIN_PaymentDetail.class, pdToRm));
-          }
-          payment.getFINPaymentDetailList().removeAll(removedPD);
-          if (strAction.equals("R")) {
-            payment.getCurrencyConversionRateDocList().removeAll(conversionRates);
-            payment.setFinancialTransactionConvertRate(BigDecimal.ZERO);
-          }
-          OBDal.getInstance().save(payment);
-
-          if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
-              && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
-            undoUsedCredit(payment, vars, invoiceDocNos);
-          }
-
-          List<FIN_Payment> creditPayments = new ArrayList<FIN_Payment>();
-          for (final FIN_Payment_Credit pc : payment.getFINPaymentCreditList()) {
-            creditPayments.add(pc.getCreditPaymentUsed());
-          }
-          for (final FIN_Payment creditPayment : creditPayments) {
-            // Update Description
-            final String payDesc = creditPayment.getDescription();
-            if (payDesc != null) {
-              final String invoiceDocNoMsg = Utility.messageBD(new DalConnectionProvider(),
-                  "APRM_CreditUsedinInvoice", vars.getLanguage());
-              if (invoiceDocNoMsg != null) {
-                final StringBuffer newDesc = new StringBuffer();
-                for (final String line : payDesc.split("\n")) {
-                  boolean include = true;
-                  if (line.startsWith(invoiceDocNoMsg.substring(0,
-                      invoiceDocNoMsg.lastIndexOf("%s")))) {
-                    for (final String docNo : invoiceDocNos) {
-                      if (line.indexOf(docNo) > 0) {
-                        include = false;
-                        break;
+            for (final FIN_Payment creditPayment : creditPayments) {
+              // Update Description
+              final String payDesc = creditPayment.getDescription();
+              if (payDesc != null) {
+                final String invoiceDocNoMsg = Utility.messageBD(new DalConnectionProvider(),
+                    "APRM_CreditUsedinInvoice", vars.getLanguage());
+                if (invoiceDocNoMsg != null) {
+                  final StringBuffer newDesc = new StringBuffer();
+                  for (final String line : payDesc.split("\n")) {
+                    boolean include = true;
+                    if (line.startsWith(invoiceDocNoMsg.substring(0,
+                        invoiceDocNoMsg.lastIndexOf("%s")))) {
+                      for (final String docNo : invoiceDocNos) {
+                        if (line.indexOf(docNo) > 0) {
+                          include = false;
+                          break;
+                        }
                       }
                     }
+                    if (include) {
+                      newDesc.append(line);
+                      if (!"".equals(line))
+                        newDesc.append("\n");
+                    }
                   }
-                  if (include) {
-                    newDesc.append(line);
-                    if (!"".equals(line))
-                      newDesc.append("\n");
-                  }
+                  // Truncate Description to keep length as 255
+                  creditPayment.setDescription(newDesc.toString().length() > 255 ? newDesc
+                      .toString().substring(0, 255) : newDesc.toString());
                 }
-                // Truncate Description to keep length as 255
-                creditPayment.setDescription(newDesc.toString().length() > 255 ? newDesc.toString()
-                    .substring(0, 255) : newDesc.toString());
               }
             }
           }
@@ -939,7 +993,9 @@
               return;
             }
             // Payment not in Awaiting Execution
-            if (!"RPAE".equals(payment.getStatus())) {
+            boolean restorePaidAmounts = (FIN_Utility.seqnumberpaymentstatus(payment.getStatus())) < (FIN_Utility
+                .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
+            if (!restorePaidAmounts) {
               msg.setType("Error");
               msg.setTitle(Utility.messageBD(conProvider, "Error", language));
               msg.setMessage(Utility.parseTranslation(conProvider, vars, language,
@@ -962,6 +1018,10 @@
             for (final FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) {
               for (final FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                   .getFINPaymentScheduleDetailList()) {
+                Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid();
+                if (invoicePaidold) {
+                  paymentScheduleDetail.setInvoicePaid(false);
+                }
                 BigDecimal outStandingAmt = BigDecimal.ZERO;
 
                 if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
@@ -1049,6 +1109,7 @@
               }
               OBDal.getInstance().flush();
               removedPDS.clear();
+
             }
             if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                 && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_ReconciliationProcess.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_ReconciliationProcess.java	Tue Feb 11 12:19:57 2014 +0100
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2011 Openbravo SLU
+ * All portions are Copyright (C) 2010-2013 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -34,6 +34,9 @@
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.financialmgmt.payment.FIN_BankStatement;
+import org.openbravo.model.financialmgmt.payment.FIN_FinaccTransaction;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentDetail;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
 import org.openbravo.model.financialmgmt.payment.FIN_Reconciliation;
 import org.openbravo.model.financialmgmt.payment.FIN_ReconciliationLine_v;
 import org.openbravo.scheduling.ProcessBundle;
@@ -105,6 +108,27 @@
         OBDal.getInstance().save(reconciliation);
         OBDal.getInstance().flush();
 
+        Boolean invoicePaidold = false;
+        for (FIN_FinaccTransaction finacctransaction : reconciliation.getFINFinaccTransactionList()) {
+          for (FIN_PaymentDetail pd : finacctransaction.getFinPayment().getFINPaymentDetailList()) {
+            for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+              invoicePaidold = psd.isInvoicePaid();
+              if (!invoicePaidold) {
+                if ((FIN_Utility.invoicePaymentStatus(finacctransaction.getFinPayment()
+                    .getPaymentMethod(), reconciliation.getAccount(), finacctransaction
+                    .getFinPayment().isReceipt()).equals(finacctransaction.getFinPayment()
+                    .getStatus()))) {
+                  psd.setInvoicePaid(true);
+                }
+                if (psd.isInvoicePaid()) {
+                  FIN_Utility.updatePaymentAmounts(psd);
+                }
+              }
+            }
+          }
+          FIN_Utility.updateBusinessPartnerCredit(finacctransaction.getFinPayment());
+        }
+
         // ***********************
         // Reactivate Reconciliation
         // ***********************
@@ -135,6 +159,31 @@
         reconciliation.setAprmProcessRec("P");
         OBDal.getInstance().save(reconciliation);
         OBDal.getInstance().flush();
+        Boolean invoicePaidold = false;
+
+        for (FIN_FinaccTransaction finacctransaction : reconciliation.getFINFinaccTransactionList()) {
+          for (FIN_PaymentDetail pd : finacctransaction.getFinPayment().getFINPaymentDetailList()) {
+            for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+              invoicePaidold = psd.isInvoicePaid();
+              if (invoicePaidold) {
+                if (FIN_Utility.invoicePaymentStatus(
+                    finacctransaction.getFinPayment().getPaymentMethod(),
+                    reconciliation.getAccount(), finacctransaction.getFinPayment().isReceipt())
+                    .equals(finacctransaction.getFinPayment().getStatus())) {
+                  boolean restore = (FIN_Utility.seqnumberpaymentstatus(finacctransaction
+                      .getFinPayment().getStatus())) <= (FIN_Utility
+                      .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(finacctransaction
+                          .getFinPayment().getPaymentMethod(), reconciliation.getAccount(),
+                          finacctransaction.getFinPayment().isReceipt())));
+                  if (restore) {
+                    FIN_Utility.restorePaidAmounts(psd);
+                  }
+                }
+              }
+            }
+          }
+        }
+
       }
       reconciliation.setProcessNow(false);
       OBDal.getInstance().save(reconciliation);
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_TransactionProcess.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_TransactionProcess.java	Tue Feb 11 12:19:57 2014 +0100
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010 Openbravo SLU
+ * All portions are Copyright (C) 2013 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -38,6 +38,8 @@
 import org.openbravo.model.financialmgmt.payment.FIN_FinaccTransaction;
 import org.openbravo.model.financialmgmt.payment.FIN_FinancialAccount;
 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.scheduling.ProcessBundle;
 
 public class FIN_TransactionProcess implements org.openbravo.scheduling.Process {
@@ -97,6 +99,21 @@
             if (transaction.getDescription() == null || "".equals(transaction.getDescription())) {
               transaction.setDescription(payment.getDescription());
             }
+            Boolean invoicePaidold = false;
+            for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
+              for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+                invoicePaidold = psd.isInvoicePaid();
+                if (!invoicePaidold) {
+                  if ((FIN_Utility.invoicePaymentStatus(payment).equals(payment.getStatus()))) {
+                    psd.setInvoicePaid(true);
+                  }
+                  if (psd.isInvoicePaid()) {
+                    FIN_Utility.updatePaymentAmounts(psd);
+                  }
+                }
+              }
+            }
+            FIN_Utility.updateBusinessPartnerCredit(payment);
           } else {
             transaction.setStatus(transaction.getDepositAmount().compareTo(
                 transaction.getPaymentAmount()) > 0 ? "RDNC" : "PWNC");
@@ -110,6 +127,7 @@
           OBDal.getInstance().save(transaction);
           OBDal.getInstance().flush();
           bundle.setResult(msg);
+
         } else if (strAction.equals("R")) {
           // ***********************
           // Reactivate Transaction
@@ -155,6 +173,20 @@
           OBDal.getInstance().flush();
           FIN_Payment payment = transaction.getFinPayment();
           if (payment != null) {
+            Boolean invoicePaidold = false;
+            for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
+              for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
+                invoicePaidold = psd.isInvoicePaid();
+                if (invoicePaidold) {
+                  boolean restore = (FIN_Utility.seqnumberpaymentstatus(payment.isReceipt() ? "RPR"
+                      : "PPM")) < (FIN_Utility.seqnumberpaymentstatus(FIN_Utility
+                      .invoicePaymentStatus(payment)));
+                  if (restore) {
+                    FIN_Utility.restorePaidAmounts(psd);
+                  }
+                }
+              }
+            }
             payment.setStatus(payment.isReceipt() ? "RPR" : "PPM");
             transaction.setStatus(payment.isReceipt() ? "RPR" : "PPM");
             OBDal.getInstance().save(payment);
@@ -164,6 +196,8 @@
           }
           OBDal.getInstance().save(transaction);
           OBDal.getInstance().flush();
+          bundle.setResult(msg);
+
         }
         bundle.setResult(msg);
       } finally {
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java	Tue Feb 11 13:15:41 2014 +0530
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java	Tue Feb 11 12:19:57 2014 +0100
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2012 Openbravo SLU
+ * All portions are Copyright (C) 2010-2013 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -43,6 +43,7 @@
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
+import org.openbravo.advpaymentmngt.process.FIN_AddPayment;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.secureApp.VariablesSecureApp;
@@ -1081,6 +1082,36 @@
   }
 
   /**
+   * Returns a list of Payment Status. If isConfirmed equals true, then the status returned are
+   * confirmed payments. Else they are pending of execution
+   * 
+   */
+  private static List<String> getListPaymentConfirmedOrNot(Boolean isConfirmed,
+      FIN_PaymentScheduleDetail psd) {
+
+    List<String> listPaymentConfirmedOrNot = new ArrayList<String>();
+    OBContext.setAdminMode(true);
+    try {
+      final OBCriteria<org.openbravo.model.ad.domain.List> obCriteria = OBDal.getInstance()
+          .createCriteria(org.openbravo.model.ad.domain.List.class);
+      obCriteria.add(Restrictions.eq(org.openbravo.model.ad.domain.List.PROPERTY_REFERENCE + ".id",
+          "575BCB88A4694C27BC013DE9C73E6FE7"));
+      List<org.openbravo.model.ad.domain.List> adRefList = obCriteria.list();
+      for (org.openbravo.model.ad.domain.List adRef : adRefList) {
+        if (isConfirmed.equals(isPaymentConfirmed(adRef.getSearchKey(), psd))) {
+          listPaymentConfirmedOrNot.add(adRef.getSearchKey());
+        }
+      }
+      return listPaymentConfirmedOrNot;
+    } catch (Exception e) {
+      log4j.error("Error building the payment confirmed list", e);
+      return null;
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+  }
+
+  /**
    * Returns a list confirmed Payment Status
    * 
    */
@@ -1089,6 +1120,14 @@
   }
 
   /**
+   * Returns a list confirmed Payment Status
+   * 
+   */
+  public static List<String> getListPaymentConfirmed(FIN_PaymentScheduleDetail psd) {
+    return getListPaymentConfirmedOrNot(true, psd);
+  }
+
+  /**
    * Returns a list not confirmed Payment Status
    * 
    */
@@ -1097,6 +1136,14 @@
   }
 
   /**
+   * Returns a list not confirmed Payment Status
+   * 
+   */
+  public static List<String> getListPaymentNotConfirmed(FIN_PaymentScheduleDetail psd) {
+    return getListPaymentConfirmedOrNot(false, psd);
+  }
+
+  /**
    * Returns the legal entity of the given organization
    * 
    * @param org
@@ -1270,4 +1317,170 @@
 
     return ((Long) qry.list().get(0) > Long.parseLong("0"));
   }
+
+  /**
+   * Returns the invoice payment status value configured in the payment method in the financial
+   * account for a payment
+   */
+  public static String invoicePaymentStatus(FIN_Payment payment) {
+    return invoicePaymentStatus(payment.getPaymentMethod(), payment.getAccount(),
+        payment.isReceipt());
+  }
+
+  /**
+   * Returns the invoice payment status value configured in the payment method in the financial
+   * account for a payment
+   */
+  public static String invoicePaymentStatus(FIN_PaymentMethod paymentMethod,
+      FIN_FinancialAccount financialAccount, boolean isReceipt) {
+    String status = null;
+    for (FinAccPaymentMethod finaccpaymentmethod : financialAccount
+        .getFinancialMgmtFinAccPaymentMethodList()) {
+      if (finaccpaymentmethod.getPaymentMethod().equals(paymentMethod)) {
+        if (isReceipt) {
+          status = finaccpaymentmethod.getPayinInvoicepaidstatus();
+        } else {
+          status = finaccpaymentmethod.getPayoutInvoicepaidstatus();
+        }
+      }
+    }
+    return status;
+  }
+
+  /**
+   * This function should only be called when it should update the payment amounts
+   */
+  public static void updatePaymentAmounts(FIN_PaymentScheduleDetail psd) {
+
+    if (psd.getInvoicePaymentSchedule() != null) {
+      BusinessPartner bPartner = psd.getInvoicePaymentSchedule().getInvoice().getBusinessPartner();
+      BigDecimal creditUsed = bPartner.getCreditUsed();
+      BigDecimal amountWithSign = psd.getInvoicePaymentSchedule().getInvoice().isSalesTransaction() ? psd
+          .getAmount() : psd.getAmount().negate();
+      creditUsed = creditUsed.subtract(amountWithSign);
+      bPartner.setCreditUsed(creditUsed);
+      OBDal.getInstance().save(bPartner);
+      FIN_AddPayment.updatePaymentScheduleAmounts(psd.getInvoicePaymentSchedule(), psd.getAmount(),
+          psd.getWriteoffAmount());
+    }
+    if (psd.getOrderPaymentSchedule() != null) {
+      FIN_AddPayment.updatePaymentScheduleAmounts(psd.getOrderPaymentSchedule(), psd.getAmount(),
+          psd.getWriteoffAmount());
+    }
+    if (psd.getPaymentDetails().isPrepayment() && psd.getOrderPaymentSchedule() == null
+        && psd.getInvoicePaymentSchedule() == null) {
+      // This PSD is credit
+      BusinessPartner bPartner = psd.getPaymentDetails().getFinPayment().getBusinessPartner();
+      BigDecimal creditUsed = bPartner.getCreditUsed();
+      BigDecimal amountWithSign = psd.getPaymentDetails().getFinPayment().isReceipt() ? psd
+          .getAmount() : psd.getAmount().negate();
+      creditUsed = creditUsed.subtract(amountWithSign);
+      bPartner.setCreditUsed(creditUsed);
+      OBDal.getInstance().save(bPartner);
+    }
+
+  }
+
+  public static void updateBusinessPartnerCredit(FIN_Payment payment) {
+    // When credit is used (consumed) we compensate so_creditused as this amount is already
+    // included in the payment details. Credit consumed should not affect to so_creditused
+    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
+        && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
+      BusinessPartner bp = payment.getBusinessPartner();
+      if (payment.isReceipt()) {
+        bp.setCreditUsed(bp.getCreditUsed().add(payment.getUsedCredit()));
+      } else {
+        bp.setCreditUsed(bp.getCreditUsed().subtract(payment.getUsedCredit()));
+      }
+      OBDal.getInstance().save(bp);
+    }
+  }
+
+  /**
+   * Returns the secuence number of payment status in reference list
+   * 
+   * 
+   */
+  public static int seqnumberpaymentstatus(String status) {
+    List<Object> parameters = new ArrayList<Object>();
+    parameters.add(status);
+    int result = Integer.parseInt((String) CallStoredProcedure.getInstance().call(
+        "aprm_seqnumberpaymentstatus", parameters, null));
+
+    return result;
+  }
+
+  /**
+   * This function should only be called when it should update the payment amounts
+   */
+  public static void restorePaidAmounts(FIN_PaymentScheduleDetail paymentScheduleDetail) {
+
+    BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount();
+    BigDecimal psdAmount = paymentScheduleDetail.getAmount();
+    BigDecimal amount = psdAmount.add(psdWriteoffAmount);
+    BusinessPartner businessPartner = paymentScheduleDetail.getPaymentDetails().getFinPayment()
+        .getBusinessPartner();
+    if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
+
+      FIN_AddPayment.updatePaymentScheduleAmounts(
+          paymentScheduleDetail.getInvoicePaymentSchedule(), psdAmount.negate(),
+          psdWriteoffAmount.negate());
+      // BP SO_CreditUsed
+      businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule().getInvoice()
+          .getBusinessPartner();
+      if (paymentScheduleDetail.getPaymentDetails().getFinPayment().isReceipt()) {
+        increaseCustomerCredit(businessPartner, amount);
+      } else {
+        decreaseCustomerCredit(businessPartner, amount);
+      }
+
+    }
+    if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
+      FIN_AddPayment.updatePaymentScheduleAmounts(paymentScheduleDetail.getOrderPaymentSchedule(),
+          psdAmount.negate(), psdWriteoffAmount.negate());
+    }
+    // when generating credit for a BP SO_CreditUsed is also updated
+    if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
+        && paymentScheduleDetail.getOrderPaymentSchedule() == null
+        && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
+        && !paymentScheduleDetail.getPaymentDetails().isRefund()) {
+      // BP SO_CreditUsed
+      if (paymentScheduleDetail.getPaymentDetails().getFinPayment().isReceipt()) {
+        increaseCustomerCredit(businessPartner, amount);
+      } else {
+        decreaseCustomerCredit(businessPartner, amount);
+      }
+    }
+    paymentScheduleDetail.setInvoicePaid(false);
+    OBDal.getInstance().save(paymentScheduleDetail);
+
+  }
+
+  /**
+   * Method used to update the credit used when the user doing invoice processing or payment
+   * processing
+   * 
+   * @param amount
+   *          Payment amount
+   */
+  private static void updateCustomerCredit(BusinessPartner businessPartner, BigDecimal amount,
+      boolean add) {
+    BigDecimal creditUsed = businessPartner.getCreditUsed();
+    if (add) {
+      creditUsed = creditUsed.add(amount);
+    } else {
+      creditUsed = creditUsed.subtract(amount);
+    }
+    businessPartner.setCreditUsed(creditUsed);
+    OBDal.getInstance().save(businessPartner);
+    // OBDal.getInstance().flush();
+  }
+
+  private static void increaseCustomerCredit(BusinessPartner businessPartner, BigDecimal amount) {
+    updateCustomerCredit(businessPartner, amount, true);
+  }
+
+  private static void decreaseCustomerCredit(BusinessPartner businessPartner, BigDecimal amount) {
+    updateCustomerCredit(businessPartner, amount, false);
+  }
 }
--- a/src-db/database/model/tables/FIN_FINACC_PAYMENTMETHOD.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/src-db/database/model/tables/FIN_FINACC_PAYMENTMETHOD.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -125,6 +125,14 @@
         <default><![CDATA[N]]></default>
         <onCreateDefault/>
       </column>
+      <column name="PAYIN_INVOICEPAIDSTATUS" primaryKey="false" required="true" type="VARCHAR" size="60" autoIncrement="false">
+        <default><![CDATA[RPR]]></default>
+        <onCreateDefault/>
+      </column>
+      <column name="PAYOUT_INVOICEPAIDSTATUS" primaryKey="false" required="true" type="VARCHAR" size="60" autoIncrement="false">
+        <default><![CDATA[PPM]]></default>
+        <onCreateDefault/>
+      </column>
       <foreign-key foreignTable="AD_CLIENT" name="FIN_FINACC_PAYMETHOD_CLIENT">
         <reference local="AD_CLIENT_ID" foreign="AD_CLIENT_ID"/>
       </foreign-key>
--- a/src-db/database/model/tables/FIN_PAYMENT_SCHEDULEDETAIL.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/src-db/database/model/tables/FIN_PAYMENT_SCHEDULEDETAIL.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -97,6 +97,10 @@
         <default><![CDATA[0]]></default>
         <onCreateDefault/>
       </column>
+      <column name="ISINVOICEPAID" primaryKey="false" required="true" type="CHAR" size="1" autoIncrement="false">
+        <default><![CDATA[N]]></default>
+        <onCreateDefault/>
+      </column>
       <foreign-key foreignTable="AD_CLIENT" name="FIN_AD_CLIENT_SCHEDULEDETAIL">
         <reference local="AD_CLIENT_ID" foreign="AD_CLIENT_ID"/>
       </foreign-key>
@@ -149,5 +153,6 @@
         <index-column name="FIN_PAYMENT_DETAIL_ID"/>
       </index>
       <check name="FIN_PAY_SCHE_DETAIL_ISCANC_CHK"><![CDATA[ISCANCELED IN ('Y', 'N')]]></check>
+      <check name="FIN_PAY_SCHE_DETAIL_ISPAID_CHK"><![CDATA[ISINVOICEPAID IN ('Y', 'N')]]></check>
     </table>
   </database>
--- a/src-db/database/sourcedata/AD_COLUMN.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/src-db/database/sourcedata/AD_COLUMN.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -223246,7 +223246,7 @@
 <!--13A5B506645546CA8054A88CFD263DF0-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
 <!--13A5B506645546CA8054A88CFD263DF0-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--13A5B506645546CA8054A88CFD263DF0-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
-<!--13A5B506645546CA8054A88CFD263DF0-->  <SQLLOGIC><![CDATA[SELECT coalesce(sum(psd.doubtfuldebt_amount),0) FROM fin_payment_scheduledetail psd left join fin_payment_detail pd on psd.fin_payment_detail_id = pd.fin_payment_detail_id left join fin_payment p on pd.fin_payment_id = p.fin_payment_id WHERE psd.fin_payment_schedule_invoice = fin_payment_schedule_id and aprm_ispaymentconfirmed(p.status, psd.fin_payment_scheduledetail_id) = 'N']]></SQLLOGIC>
+<!--13A5B506645546CA8054A88CFD263DF0-->  <SQLLOGIC><![CDATA[SELECT coalesce(sum(psd.doubtfuldebt_amount),0) FROM fin_payment_scheduledetail psd left join fin_payment_detail pd on psd.fin_payment_detail_id = pd.fin_payment_detail_id left join fin_payment p on pd.fin_payment_id = p.fin_payment_id WHERE psd.fin_payment_schedule_invoice = fin_payment_schedule_id and psd.isinvoicepaid = 'N']]></SQLLOGIC>
 <!--13A5B506645546CA8054A88CFD263DF0--></AD_COLUMN>
 
 <!--13AB438B6900462FB3B92343175BFDD2--><AD_COLUMN>
@@ -228818,7 +228818,7 @@
 <!--2D56F14A0C524D8F95282389F1A45878-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
 <!--2D56F14A0C524D8F95282389F1A45878-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
 <!--2D56F14A0C524D8F95282389F1A45878-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
-<!--2D56F14A0C524D8F95282389F1A45878-->  <SQLLOGIC><![CDATA[SELECT coalesce(sum(psd.doubtfuldebt_amount),0) FROM fin_payment_scheduledetail psd left join fin_payment_detail pd on psd.fin_payment_detail_id = pd.fin_payment_detail_id left join fin_payment p on pd.fin_payment_id = p.fin_payment_id WHERE psd.fin_payment_schedule_invoice = fin_payment_schedule_id and aprm_ispaymentconfirmed(p.status, psd.fin_payment_scheduledetail_id) = 'N']]></SQLLOGIC>
+<!--2D56F14A0C524D8F95282389F1A45878-->  <SQLLOGIC><![CDATA[SELECT coalesce(sum(psd.doubtfuldebt_amount),0) FROM fin_payment_scheduledetail psd left join fin_payment_detail pd on psd.fin_payment_detail_id = pd.fin_payment_detail_id left join fin_payment p on pd.fin_payment_id = p.fin_payment_id WHERE psd.fin_payment_schedule_invoice = fin_payment_schedule_id and psd.isinvoicepaid = 'N']]></SQLLOGIC>
 <!--2D56F14A0C524D8F95282389F1A45878--></AD_COLUMN>
 
 <!--2D699F3974F64AFD8A48DC90748F4DBE--><AD_COLUMN>
@@ -232216,6 +232216,44 @@
 <!--4028C9BC2DA5C491012DA689D11F03BD-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--4028C9BC2DA5C491012DA689D11F03BD--></AD_COLUMN>
 
+<!--404453830A9D4BDB8D6F8B260BAE0CEC--><AD_COLUMN>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_COLUMN_ID><![CDATA[404453830A9D4BDB8D6F8B260BAE0CEC]]></AD_COLUMN_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <NAME><![CDATA[Payout_Invoicepaidstatus]]></NAME>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <DESCRIPTION><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></DESCRIPTION>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <HELP><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></HELP>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <COLUMNNAME><![CDATA[Payout_Invoicepaidstatus]]></COLUMNNAME>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_TABLE_ID><![CDATA[AC389EBD8A774AAE8223A77F692983D8]]></AD_TABLE_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_REFERENCE_ID><![CDATA[17]]></AD_REFERENCE_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_REFERENCE_VALUE_ID><![CDATA[575BCB88A4694C27BC013DE9C73E6FE7]]></AD_REFERENCE_VALUE_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_VAL_RULE_ID><![CDATA[1D824F88E32F4282B26C48B5A910B006]]></AD_VAL_RULE_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <FIELDLENGTH><![CDATA[60]]></FIELDLENGTH>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <DEFAULTVALUE><![CDATA[PPM]]></DEFAULTVALUE>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISKEY><![CDATA[N]]></ISKEY>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISPARENT><![CDATA[N]]></ISPARENT>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISMANDATORY><![CDATA[Y]]></ISMANDATORY>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISUPDATEABLE><![CDATA[Y]]></ISUPDATEABLE>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISIDENTIFIER><![CDATA[N]]></ISIDENTIFIER>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <SEQNO><![CDATA[330]]></SEQNO>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISSELECTIONCOLUMN><![CDATA[N]]></ISSELECTIONCOLUMN>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_ELEMENT_ID><![CDATA[89ED718916DC4A30B921711EB8D020BD]]></AD_ELEMENT_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISSESSIONATTR><![CDATA[N]]></ISSESSIONATTR>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISSECONDARYKEY><![CDATA[N]]></ISSECONDARYKEY>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISDESENCRYPTABLE><![CDATA[N]]></ISDESENCRYPTABLE>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <DEVELOPMENTSTATUS><![CDATA[RE]]></DEVELOPMENTSTATUS>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <POSITION><![CDATA[33]]></POSITION>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISTRANSIENT><![CDATA[N]]></ISTRANSIENT>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISAUTOSAVE><![CDATA[Y]]></ISAUTOSAVE>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
+<!--404453830A9D4BDB8D6F8B260BAE0CEC--></AD_COLUMN>
+
 <!--4063E40CC97C4EC996A2DA6D692DD877--><AD_COLUMN>
 <!--4063E40CC97C4EC996A2DA6D692DD877-->  <AD_COLUMN_ID><![CDATA[4063E40CC97C4EC996A2DA6D692DD877]]></AD_COLUMN_ID>
 <!--4063E40CC97C4EC996A2DA6D692DD877-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
@@ -292700,7 +292738,7 @@
 <!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <ISDESENCRYPTABLE><![CDATA[N]]></ISDESENCRYPTABLE>
 <!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <DEVELOPMENTSTATUS><![CDATA[RE]]></DEVELOPMENTSTATUS>
 <!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
-<!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <POSITION><![CDATA[21]]></POSITION>
+<!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <POSITION><![CDATA[24]]></POSITION>
 <!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <ISTRANSIENT><![CDATA[N]]></ISTRANSIENT>
 <!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <ISAUTOSAVE><![CDATA[Y]]></ISAUTOSAVE>
 <!--A5CF4D3408B744808F87A1E1A8F4C2E0-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
@@ -305670,6 +305708,42 @@
 <!--C5B48143197D42D2A50EB784A9DCF7EB-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--C5B48143197D42D2A50EB784A9DCF7EB--></AD_COLUMN>
 
+<!--C5CABD48EA774B8289401E670504371C--><AD_COLUMN>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_COLUMN_ID><![CDATA[C5CABD48EA774B8289401E670504371C]]></AD_COLUMN_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--C5CABD48EA774B8289401E670504371C-->  <NAME><![CDATA[Invoice Paid]]></NAME>
+<!--C5CABD48EA774B8289401E670504371C-->  <DESCRIPTION><![CDATA[A flag indicating whether this document type is consider paid or not.]]></DESCRIPTION>
+<!--C5CABD48EA774B8289401E670504371C-->  <HELP><![CDATA[A flag indicating whether this document type is consider paid or not.]]></HELP>
+<!--C5CABD48EA774B8289401E670504371C-->  <COLUMNNAME><![CDATA[Isinvoicepaid]]></COLUMNNAME>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_TABLE_ID><![CDATA[C0233061EA504EFEAB0483E836BBAF31]]></AD_TABLE_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_REFERENCE_ID><![CDATA[20]]></AD_REFERENCE_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <FIELDLENGTH><![CDATA[1]]></FIELDLENGTH>
+<!--C5CABD48EA774B8289401E670504371C-->  <DEFAULTVALUE><![CDATA[N]]></DEFAULTVALUE>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISKEY><![CDATA[N]]></ISKEY>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISPARENT><![CDATA[N]]></ISPARENT>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISMANDATORY><![CDATA[Y]]></ISMANDATORY>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISUPDATEABLE><![CDATA[Y]]></ISUPDATEABLE>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISIDENTIFIER><![CDATA[N]]></ISIDENTIFIER>
+<!--C5CABD48EA774B8289401E670504371C-->  <SEQNO><![CDATA[240]]></SEQNO>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISSELECTIONCOLUMN><![CDATA[N]]></ISSELECTIONCOLUMN>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_ELEMENT_ID><![CDATA[AE5F0D103EEF4E7CB86EB5A9B4801686]]></AD_ELEMENT_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISSESSIONATTR><![CDATA[N]]></ISSESSIONATTR>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISSECONDARYKEY><![CDATA[N]]></ISSECONDARYKEY>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISDESENCRYPTABLE><![CDATA[N]]></ISDESENCRYPTABLE>
+<!--C5CABD48EA774B8289401E670504371C-->  <DEVELOPMENTSTATUS><![CDATA[RE]]></DEVELOPMENTSTATUS>
+<!--C5CABD48EA774B8289401E670504371C-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--C5CABD48EA774B8289401E670504371C-->  <POSITION><![CDATA[25]]></POSITION>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISTRANSIENT><![CDATA[N]]></ISTRANSIENT>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISAUTOSAVE><![CDATA[Y]]></ISAUTOSAVE>
+<!--C5CABD48EA774B8289401E670504371C-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
+<!--C5CABD48EA774B8289401E670504371C-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
+<!--C5CABD48EA774B8289401E670504371C-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
+<!--C5CABD48EA774B8289401E670504371C--></AD_COLUMN>
+
 <!--C5E48D4E187A4B7D9F33FA4F42C8F243--><AD_COLUMN>
 <!--C5E48D4E187A4B7D9F33FA4F42C8F243-->  <AD_COLUMN_ID><![CDATA[C5E48D4E187A4B7D9F33FA4F42C8F243]]></AD_COLUMN_ID>
 <!--C5E48D4E187A4B7D9F33FA4F42C8F243-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
@@ -318151,6 +318225,44 @@
 <!--DC9B9CB15D3741F0B22AA99D28815004-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
 <!--DC9B9CB15D3741F0B22AA99D28815004--></AD_COLUMN>
 
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72--><AD_COLUMN>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_COLUMN_ID><![CDATA[DCB1C7FD660F4CBFBDD1B7E5B165DB72]]></AD_COLUMN_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <NAME><![CDATA[Payin_Invoicepaidstatus]]></NAME>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <DESCRIPTION><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></DESCRIPTION>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <HELP><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></HELP>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <COLUMNNAME><![CDATA[Payin_Invoicepaidstatus]]></COLUMNNAME>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_TABLE_ID><![CDATA[AC389EBD8A774AAE8223A77F692983D8]]></AD_TABLE_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_REFERENCE_ID><![CDATA[17]]></AD_REFERENCE_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_REFERENCE_VALUE_ID><![CDATA[575BCB88A4694C27BC013DE9C73E6FE7]]></AD_REFERENCE_VALUE_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_VAL_RULE_ID><![CDATA[27D8D0FDAE4742229DC64888DF9CB8A8]]></AD_VAL_RULE_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <FIELDLENGTH><![CDATA[60]]></FIELDLENGTH>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <DEFAULTVALUE><![CDATA[RPR]]></DEFAULTVALUE>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISKEY><![CDATA[N]]></ISKEY>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISPARENT><![CDATA[N]]></ISPARENT>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISMANDATORY><![CDATA[Y]]></ISMANDATORY>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISUPDATEABLE><![CDATA[Y]]></ISUPDATEABLE>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISIDENTIFIER><![CDATA[N]]></ISIDENTIFIER>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <SEQNO><![CDATA[320]]></SEQNO>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISSELECTIONCOLUMN><![CDATA[N]]></ISSELECTIONCOLUMN>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_ELEMENT_ID><![CDATA[6C5A25285A23464AAA86C0AD8FBE9D61]]></AD_ELEMENT_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISSESSIONATTR><![CDATA[N]]></ISSESSIONATTR>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISSECONDARYKEY><![CDATA[N]]></ISSECONDARYKEY>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISDESENCRYPTABLE><![CDATA[N]]></ISDESENCRYPTABLE>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <DEVELOPMENTSTATUS><![CDATA[RE]]></DEVELOPMENTSTATUS>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <POSITION><![CDATA[32]]></POSITION>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISTRANSIENT><![CDATA[N]]></ISTRANSIENT>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISAUTOSAVE><![CDATA[Y]]></ISAUTOSAVE>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
+<!--DCB1C7FD660F4CBFBDD1B7E5B165DB72--></AD_COLUMN>
+
 <!--DCB5B1A795534ADCB6E1B561AC0D206B--><AD_COLUMN>
 <!--DCB5B1A795534ADCB6E1B561AC0D206B-->  <AD_COLUMN_ID><![CDATA[DCB5B1A795534ADCB6E1B561AC0D206B]]></AD_COLUMN_ID>
 <!--DCB5B1A795534ADCB6E1B561AC0D206B-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/src-db/database/sourcedata/AD_ELEMENT.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/src-db/database/sourcedata/AD_ELEMENT.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -25148,6 +25148,20 @@
 <!--6BDD5E11747C51DAE040007F01013550-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
 <!--6BDD5E11747C51DAE040007F01013550--></AD_ELEMENT>
 
+<!--6C5A25285A23464AAA86C0AD8FBE9D61--><AD_ELEMENT>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <AD_ELEMENT_ID><![CDATA[6C5A25285A23464AAA86C0AD8FBE9D61]]></AD_ELEMENT_ID>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <COLUMNNAME><![CDATA[Payin_Invoicepaidstatus]]></COLUMNNAME>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <NAME><![CDATA[Invoice Paid Status]]></NAME>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <PRINTNAME><![CDATA[Invoice Paid Status]]></PRINTNAME>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <DESCRIPTION><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></DESCRIPTION>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <HELP><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></HELP>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
+<!--6C5A25285A23464AAA86C0AD8FBE9D61--></AD_ELEMENT>
+
 <!--6CF319AF55D2424888E4B8A6C8C4C789--><AD_ELEMENT>
 <!--6CF319AF55D2424888E4B8A6C8C4C789-->  <AD_ELEMENT_ID><![CDATA[6CF319AF55D2424888E4B8A6C8C4C789]]></AD_ELEMENT_ID>
 <!--6CF319AF55D2424888E4B8A6C8C4C789-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
@@ -27627,6 +27641,20 @@
 <!--8976BF563A8848EE9A25AB42C1B995D3-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
 <!--8976BF563A8848EE9A25AB42C1B995D3--></AD_ELEMENT>
 
+<!--89ED718916DC4A30B921711EB8D020BD--><AD_ELEMENT>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <AD_ELEMENT_ID><![CDATA[89ED718916DC4A30B921711EB8D020BD]]></AD_ELEMENT_ID>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <COLUMNNAME><![CDATA[Payout_Invoicepaidstatus]]></COLUMNNAME>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <NAME><![CDATA[Invoice Paid Status]]></NAME>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <PRINTNAME><![CDATA[Invoice Paid Status]]></PRINTNAME>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <DESCRIPTION><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></DESCRIPTION>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <HELP><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></HELP>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--89ED718916DC4A30B921711EB8D020BD-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
+<!--89ED718916DC4A30B921711EB8D020BD--></AD_ELEMENT>
+
 <!--8A19431CC0E020DBE040007F01013CCA--><AD_ELEMENT>
 <!--8A19431CC0E020DBE040007F01013CCA-->  <AD_ELEMENT_ID><![CDATA[8A19431CC0E020DBE040007F01013CCA]]></AD_ELEMENT_ID>
 <!--8A19431CC0E020DBE040007F01013CCA-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
@@ -29048,6 +29076,20 @@
 <!--ADFFC3B26CB61D04E040007F01013D82-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
 <!--ADFFC3B26CB61D04E040007F01013D82--></AD_ELEMENT>
 
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686--><AD_ELEMENT>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <AD_ELEMENT_ID><![CDATA[AE5F0D103EEF4E7CB86EB5A9B4801686]]></AD_ELEMENT_ID>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <COLUMNNAME><![CDATA[Isinvoicepaid]]></COLUMNNAME>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <NAME><![CDATA[Invoice Paid]]></NAME>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <PRINTNAME><![CDATA[Invoice Paid]]></PRINTNAME>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <DESCRIPTION><![CDATA[A flag indicating whether this document type is consider paid or not.]]></DESCRIPTION>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <HELP><![CDATA[A flag indicating whether this document type is consider paid or not.]]></HELP>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
+<!--AE5F0D103EEF4E7CB86EB5A9B4801686--></AD_ELEMENT>
+
 <!--AF073DA2C96FFA0CE040A8C09166378E--><AD_ELEMENT>
 <!--AF073DA2C96FFA0CE040A8C09166378E-->  <AD_ELEMENT_ID><![CDATA[AF073DA2C96FFA0CE040A8C09166378E]]></AD_ELEMENT_ID>
 <!--AF073DA2C96FFA0CE040A8C09166378E-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/src-db/database/sourcedata/AD_FIELD.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/src-db/database/sourcedata/AD_FIELD.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -270954,6 +270954,35 @@
 <!--D90513BC049C4CD5A0589E641DAFC4A0-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
 <!--D90513BC049C4CD5A0589E641DAFC4A0--></AD_FIELD>
 
+<!--D90DA624AD5C4E46AF557E13DCA6A248--><AD_FIELD>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <AD_FIELD_ID><![CDATA[D90DA624AD5C4E46AF557E13DCA6A248]]></AD_FIELD_ID>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <NAME><![CDATA[Invoice Paid Status]]></NAME>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <DESCRIPTION><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></DESCRIPTION>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <HELP><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></HELP>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <AD_TAB_ID><![CDATA[01F5E95D71544D428E1B9004B05D0298]]></AD_TAB_ID>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <AD_COLUMN_ID><![CDATA[DCB1C7FD660F4CBFBDD1B7E5B165DB72]]></AD_COLUMN_ID>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <IGNOREINWAD><![CDATA[N]]></IGNOREINWAD>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <DISPLAYLOGIC><![CDATA[@InvoicePaidStatus@='Y']]></DISPLAYLOGIC>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <DISPLAYLENGTH><![CDATA[32]]></DISPLAYLENGTH>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISREADONLY><![CDATA[N]]></ISREADONLY>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <SEQNO><![CDATA[115]]></SEQNO>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISSAMELINE><![CDATA[N]]></ISSAMELINE>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISFIELDONLY><![CDATA[N]]></ISFIELDONLY>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <SHOWINRELATION><![CDATA[N]]></SHOWINRELATION>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISFIRSTFOCUSEDFIELD><![CDATA[N]]></ISFIRSTFOCUSEDFIELD>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <STARTINODDCOLUMN><![CDATA[N]]></STARTINODDCOLUMN>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <STARTNEWLINE><![CDATA[N]]></STARTNEWLINE>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <ISSHOWNINSTATUSBAR><![CDATA[N]]></ISSHOWNINSTATUSBAR>
+<!--D90DA624AD5C4E46AF557E13DCA6A248-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
+<!--D90DA624AD5C4E46AF557E13DCA6A248--></AD_FIELD>
+
 <!--D918AFDEC57345CC899197C9FC7313B1--><AD_FIELD>
 <!--D918AFDEC57345CC899197C9FC7313B1-->  <AD_FIELD_ID><![CDATA[D918AFDEC57345CC899197C9FC7313B1]]></AD_FIELD_ID>
 <!--D918AFDEC57345CC899197C9FC7313B1-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
@@ -275874,6 +275903,35 @@
 <!--E7BACF4345EB4CEC98DC383CAF1B6D7E-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
 <!--E7BACF4345EB4CEC98DC383CAF1B6D7E--></AD_FIELD>
 
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2--><AD_FIELD>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <AD_FIELD_ID><![CDATA[E7D9E6B28CC34E2FB5271C3AF9DE7FD2]]></AD_FIELD_ID>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <NAME><![CDATA[Invoice Paid Status]]></NAME>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <DESCRIPTION><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></DESCRIPTION>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <HELP><![CDATA[State in which a invoice is considered paid. This state can be configured for each payment method and financial account.]]></HELP>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <AD_TAB_ID><![CDATA[01F5E95D71544D428E1B9004B05D0298]]></AD_TAB_ID>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <AD_COLUMN_ID><![CDATA[404453830A9D4BDB8D6F8B260BAE0CEC]]></AD_COLUMN_ID>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <IGNOREINWAD><![CDATA[N]]></IGNOREINWAD>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <DISPLAYLOGIC><![CDATA[@InvoicePaidStatus@='Y']]></DISPLAYLOGIC>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <DISPLAYLENGTH><![CDATA[32]]></DISPLAYLENGTH>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISREADONLY><![CDATA[N]]></ISREADONLY>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <SEQNO><![CDATA[220]]></SEQNO>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISSAMELINE><![CDATA[N]]></ISSAMELINE>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISFIELDONLY><![CDATA[N]]></ISFIELDONLY>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <SHOWINRELATION><![CDATA[N]]></SHOWINRELATION>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISFIRSTFOCUSEDFIELD><![CDATA[N]]></ISFIRSTFOCUSEDFIELD>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <STARTINODDCOLUMN><![CDATA[N]]></STARTINODDCOLUMN>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <STARTNEWLINE><![CDATA[N]]></STARTNEWLINE>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <ISSHOWNINSTATUSBAR><![CDATA[N]]></ISSHOWNINSTATUSBAR>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
+<!--E7D9E6B28CC34E2FB5271C3AF9DE7FD2--></AD_FIELD>
+
 <!--E7E3B49E2E2548BA873BBE6232A9871A--><AD_FIELD>
 <!--E7E3B49E2E2548BA873BBE6232A9871A-->  <AD_FIELD_ID><![CDATA[E7E3B49E2E2548BA873BBE6232A9871A]]></AD_FIELD_ID>
 <!--E7E3B49E2E2548BA873BBE6232A9871A-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/src-db/database/sourcedata/AD_REF_LIST.xml	Tue Feb 11 13:15:41 2014 +0530
+++ b/src-db/database/sourcedata/AD_REF_LIST.xml	Tue Feb 11 12:19:57 2014 +0100
@@ -8054,6 +8054,18 @@
 <!--0C2419A503014EC79C4BD92338B537DE-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
 <!--0C2419A503014EC79C4BD92338B537DE--></AD_REF_LIST>
 
+<!--0D31051729234039BD60CE31C0C1929D--><AD_REF_LIST>
+<!--0D31051729234039BD60CE31C0C1929D-->  <AD_REF_LIST_ID><![CDATA[0D31051729234039BD60CE31C0C1929D]]></AD_REF_LIST_ID>
+<!--0D31051729234039BD60CE31C0C1929D-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--0D31051729234039BD60CE31C0C1929D-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--0D31051729234039BD60CE31C0C1929D-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--0D31051729234039BD60CE31C0C1929D-->  <VALUE><![CDATA[InvoicePaidStatus]]></VALUE>
+<!--0D31051729234039BD60CE31C0C1929D-->  <NAME><![CDATA[Allow to use invoice paid status control]]></NAME>
+<!--0D31051729234039BD60CE31C0C1929D-->  <DESCRIPTION><![CDATA[Allow to use invoice paid status control]]></DESCRIPTION>
+<!--0D31051729234039BD60CE31C0C1929D-->  <AD_REFERENCE_ID><![CDATA[A26BA480E2014707B47257024C3CBFF7]]></AD_REFERENCE_ID>
+<!--0D31051729234039BD60CE31C0C1929D-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--0D31051729234039BD60CE31C0C1929D--></AD_REF_LIST>
+
 <!--0D7FF4CBD848492490B37032EF534E73--><AD_REF_LIST>
 <!--0D7FF4CBD848492490B37032EF534E73-->  <AD_REF_LIST_ID><![CDATA[0D7FF4CBD848492490B37032EF534E73]]></AD_REF_LIST_ID>
 <!--0D7FF4CBD848492490B37032EF534E73-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
Binary file src-util/modulescript/build/classes/org/openbravo/modulescript/InitializeIsPaymentPaid.class has changed
Binary file src-util/modulescript/build/classes/org/openbravo/modulescript/InitializeIsPaymentPaidData.class has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-util/modulescript/src/org/openbravo/modulescript/InitializeIsPaymentPaid.java	Tue Feb 11 12:19:57 2014 +0100
@@ -0,0 +1,41 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2013 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+package org.openbravo.modulescript;
+
+import org.apache.log4j.Logger;
+import org.openbravo.database.ConnectionProvider;
+import org.openbravo.utils.FormatUtilities;
+
+public class InitializeIsPaymentPaid extends ModuleScript {
+
+  @Override
+  public void execute() {
+    try {
+      ConnectionProvider cp = getConnectionProvider();
+      boolean isInitialized= InitializeIsPaymentPaidData.isExecuted(cp);
+      if (!isInitialized){
+        InitializeIsPaymentPaidData.initializeisinvoicepaid(cp);
+        InitializeIsPaymentPaidData.createPreference(cp);
+      }
+    } catch (Exception e) {
+      handleError(e);
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-util/modulescript/src/org/openbravo/modulescript/InitializeIsPaymentPaid_data.xsql	Tue Feb 11 12:19:57 2014 +0100
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2013 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+-->
+<SqlClass name="InitializeIsPaymentPaidData" package="org.openbravo.modulescript">
+ <SqlMethod name="select" type="preparedStatement" return="multiple">
+    <SqlMethodComment></SqlMethodComment>
+    <Sql><![CDATA[
+      SELECT '' AS isinvoicepaid
+      FROM DUAL
+      ]]>
+    </Sql>
+  </SqlMethod>
+  <SqlClassComment></SqlClassComment>
+  <SqlMethod name="initializeisinvoicepaid" type="preparedStatement" return="rowCount">
+    <SqlMethodComment></SqlMethodComment>
+    <Sql>
+     <![CDATA[ 
+        update fin_payment_scheduledetail set isinvoicepaid=(select CASE WHEN fpsd.fin_payment_detail_id is null then 'N'
+        WHEN 
+        ((aprm_seqnumberpaymentstatus(fp.status))>= (aprm_seqnumberpaymentstatus((CASE WHEN fp.isreceipt='Y' 
+        THEN Payin_Invoicepaidstatus ELSE Payout_Invoicepaidstatus END)))) THEN 'Y' ELSE 'N' END
+        from fin_payment_scheduledetail fpsd
+         left join fin_payment_detail fpd on fpsd.fin_payment_detail_id=fpd.fin_payment_detail_id
+         left join fin_payment fp on fpd.fin_payment_id=fp.fin_payment_id
+         left join fin_financial_account fa on fa.fin_financial_account_id=fp.fin_financial_account_id 
+         left join FIN_FinAcc_PaymentMethod fpm on fpm.fin_financial_account_id=fp.fin_financial_account_id 
+         and fpm.fin_paymentmethod_id=fp.fin_paymentmethod_id  
+         and fin_payment_schedule_invoice is not null
+         where fin_payment_scheduledetail.fin_payment_scheduledetail_id=fpsd.fin_payment_scheduledetail_id)
+      ]]>
+    </Sql>
+    </SqlMethod>
+    <SqlMethod name="isExecuted" type="preparedStatement" return="boolean">
+    <SqlMethodComment></SqlMethodComment>
+    <Sql>
+      <![CDATA[
+        SELECT count(*) as exist
+        FROM DUAL
+        WHERE EXISTS (SELECT 1 FROM ad_preference
+                      WHERE attribute = 'InvoicePaidStatusInitialized')
+      ]]>
+    </Sql>
+  </SqlMethod>
+   <SqlMethod name="createPreference" type="preparedStatement" return="rowcount">
+      <SqlMethodComment></SqlMethodComment>
+       <Sql> 
+       <![CDATA[ 
+           INSERT INTO ad_preference (
+           ad_preference_id, ad_client_id, ad_org_id, isactive,
+           createdby, created, updatedby, updated,attribute
+           ) VALUES (
+           get_uuid(), '0', '0', 'Y', '0', NOW(), '0', NOW(),'InvoicePaidStatusInitialized')
+         ]]>
+        </Sql>
+   </SqlMethod>
+</SqlClass>
\ No newline at end of file