src-db/database/model/functions/C_SETTLEMENT_POST.xml
author Juan Pablo Aroztegi <juanpablo.aroztegi@openbravo.com>
Wed, 03 Sep 2008 17:55:37 +0000
changeset 1605 8a0fe0193bef
parent 1349 ffd9daaff911
child 1929 ad0353d93b0f
permissions -rw-r--r--
Merge r2.5x intro trunk
<?xml version="1.0"?>
  <database name="FUNCTION C_SETTLEMENT_POST">
    <function name="C_SETTLEMENT_POST" type="NULL">
      <parameter name="p_pinstance_id" type="VARCHAR" mode="in">
        <default/>
      </parameter>
      <parameter name="p_settlement_id" type="VARCHAR" mode="in">
        <default/>
      </parameter>
      <body><![CDATA[/*************************************************************************
* The contents of this file are subject to the Openbravo  Public  License
* Version  1.0  (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 SL
* All portions are Copyright (C) 2001-2006 Openbravo SL
* All Rights Reserved.
* Contributor(s):  ______________________________________.
************************************************************************/
  --  Logistice
  v_ResultStr VARCHAR2(2000):='';
  v_Message VARCHAR2(2000):='';
  v_Result NUMBER:=1; -- 0=failure
  v_Record_ID VARCHAR2(32) ;
  v_AD_User_ID VARCHAR2(32) ;
  v_AD_Client_ID VARCHAR2(32) ;
  v_AD_Org_ID VARCHAR2(32) ;
  v_Processed CHAR(1) ;
  v_Currency VARCHAR2(32);
  v_Date DATE;
  v_DateAcct DATE;
  v_CashBook_ISO_Code VARCHAR(10) ;
  v_Record_Description VARCHAR2(2000):='';
  v_Debt_Payment_ID VARCHAR2(32) ;
  v_isGenerated char(1) ;
  --Added by Psarobe
  v_documentno_Dp_Management VARCHAR2(40);
  v_Datetrx DATE;
  v_Dp_Managementline_ID VARCHAR2(32);
  v_nameBankstatement VARCHAR2 (60);
  v_dateBankstatement DATE;
  v_nameCash VARCHAR2 (60);
  v_dateCash DATE;
  v_documentno_Settlement VARCHAR2(20);
  v_dateSettlement DATE;
  v_column_identifier VARCHAR2(4000);
  v_Cashline_ID VARCHAR2(32);
  v_Bankstatement_ID VARCHAR2(32);
  --  Parameter
  TYPE RECORD IS REF CURSOR;
    Cur_Parameter RECORD;
    --  Parameter Variables
    v_Aux NUMBER;
    v_CanceledNotChargeAmt NUMBER:=0;
    v_GeneratedAmt NUMBER:=0;
    v_ChargedAmt NUMBER:=0;
    -- For WithHolding 
    v_CanceledNotChargeAmt_WH NUMBER:=0;
    v_GeneratedAmt_WH NUMBER:=0;
    v_ChargedAmt_WH NUMBER:=0;
    --
    v_ForcedOrg NUMBER;
    v_ManualAmt NUMBER:=0;
    FINISH_PROCESS BOOLEAN:=false;
  BEGIN
    IF(p_PInstance_ID IS NOT NULL) THEN
      --  Update AD_PInstance
      DBMS_OUTPUT.PUT_LINE('Updating PInstance - Processing ' || p_PInstance_ID) ;
      v_ResultStr:='PInstanceNotFound';
      AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'Y', NULL, NULL) ;
      --  Get Parameters
      v_ResultStr:='ReadingParameters';
      FOR Cur_Parameter IN
        (SELECT i.Record_ID,
          i.AD_User_ID,
          p.ParameterName,
          p.P_String,
          p.P_Number,
          p.P_Date
        FROM AD_PInstance i
        LEFT JOIN AD_PInstance_Para p
          ON i.AD_PInstance_ID=p.AD_PInstance_ID
        WHERE i.AD_PInstance_ID=p_PInstance_ID
        ORDER BY p.SeqNo
        )
      LOOP
        v_Record_ID:=Cur_Parameter.Record_ID;
      END LOOP; --  Get Parameter
      DBMS_OUTPUT.PUT_LINE('  Record_ID=' || v_Record_ID) ;
    ELSE
      DBMS_OUTPUT.PUT_LINE('--<<C_Settlement_Post>>') ;
      v_Record_ID:=p_Settlement_ID;
    END IF;
  BEGIN --BODY
    SELECT UpdatedBy, AD_Client_ID, AD_Org_ID, Processed,
      C_Currency_ID, DATETRX, DateAcct, IsGenerated
    INTO v_AD_User_ID, v_AD_Client_ID, v_AD_Org_ID, v_Processed,
      v_Currency, v_Date, v_DateAcct, v_IsGenerated
    FROM C_SETTLEMENT
    WHERE C_Settlement_ID=v_Record_ID;
    IF(v_Processed='Y') THEN
      --Checking restrictions for unprocessing
      SELECT COUNT(*), MAX(C_DEBT_PAYMENT_ID)
      INTO v_Aux, v_Debt_Payment_ID
      FROM C_DEBT_PAYMENT
      WHERE(C_BANKSTATEMENTLINE_ID IS NOT NULL
        OR C_CASHLINE_ID IS NOT NULL)
        AND(C_SETTLEMENT_GENERATE_ID=v_Record_ID
        OR C_SETTLEMENT_CANCEL_ID=v_Record_ID) ;
      IF v_Aux<>0 THEN
	  	 SELECT AD_COLUMN_IDENTIFIER_STD('C_Debt_Payment',TO_CHAR(C_DEBT_PAYMENT.C_Debt_Payment_Id)), C_BANKSTATEMENTLINE_ID, C_CASHLINE_ID
		 INTO v_column_identifier, v_Bankstatement_ID,v_Cashline_ID
		 FROM C_DEBT_PAYMENT WHERE C_DEBT_PAYMENT_ID = v_Debt_Payment_ID;
		 	  IF v_Bankstatement_ID IS NOT NULL THEN
			  	 SELECT  C_BANKSTATEMENT.NAME, C_BANKSTATEMENT.STATEMENTDATE
				 INTO v_nameBankstatement, v_dateBankstatement
			  	 FROM C_BANKSTATEMENT, C_BANKSTATEMENTLINE
				 WHERE C_BANKSTATEMENT.C_BANKSTATEMENT_ID = C_BANKSTATEMENTLINE.C_BANKSTATEMENT_ID
				 AND C_BANKSTATEMENTLINE.C_DEBT_PAYMENT_ID = v_Debt_Payment_ID;
				 RAISE_APPLICATION_ERROR(-20000, '@Debtpayment@'||v_column_identifier||' '||'@ConciliatedDebtPaymentBank@'||v_nameBankstatement||' '||'@Bydate@'||v_dateBankstatement) ;
			  END IF;
			  IF v_Cashline_ID IS NOT NULL THEN
			  	 SELECT C_CASH.NAME, C_CASH.STATEMENTDATE
				 INTO v_nameCash, v_dateCash
				 FROM C_CASH, C_CASHLINE
				 WHERE C_CASH.C_CASH_ID = C_CASHLINE.C_CASH_ID
				 AND C_CASHLINE.C_DEBT_PAYMENT_ID = v_Debt_Payment_ID;
         		 RAISE_APPLICATION_ERROR(-20000, '@Debtpayment@'||v_column_identifier||' '||'@ConciliatedDebtPaymentCash@'||v_nameCash||' '||'@Bydate@'||v_dateCash) ;
			  END IF;
      END IF;
      IF(NOT FINISH_PROCESS) THEN
        SELECT COUNT(*), MAX(C_Debt_Payment_Id)
        INTO v_Aux, v_Debt_Payment_ID
        FROM C_DEBT_PAYMENT
        WHERE C_SETTLEMENT_CANCEL_ID IS NOT NULL
          AND C_SETTLEMENT_GENERATE_ID=v_Record_ID;
        IF v_Aux<>0 THEN
		  SELECT documentno, datetrx, AD_COLUMN_IDENTIFIER_STD('C_Debt_Payment', TO_CHAR(C_DEBT_PAYMENT.C_Debt_Payment_Id))
		  INTO v_documentno_Settlement, v_dateSettlement, v_column_identifier
		  FROM C_SETTLEMENT, C_DEBT_PAYMENT
		  WHERE C_SETTLEMENT.C_Settlement_Id = C_DEBT_PAYMENT.C_settlement_cancel_Id
		  and C_DEBT_PAYMENT.C_Debt_Payment_Id = v_Debt_Payment_ID;
          RAISE_APPLICATION_ERROR(-20000, '@Debtpayment@'||v_column_identifier||' '||'@GenerateDebtPaymentManaged@'||v_documentno_Settlement||' '||'@Bydate@'||v_dateSettlement) ;
        END IF;
      END IF;--FINISH_PROCESS
      IF(NOT FINISH_PROCESS) THEN
        SELECT COUNT(*), MAX(ml.C_DP_ManagementLine_Id)
        INTO v_Aux, v_Dp_Managementline_Id
        FROM C_DP_ManagementLine ml,
          C_DP_Management m,
          C_Debt_Payment dp
        WHERE ml.C_DP_Management_ID=m.C_DP_Management_ID
          AND ml.C_Debt_Payment_ID=dp.C_Debt_Payment_ID
          AND dp.C_Settlement_Generate_ID=v_Record_ID
          AND m.processed='Y';
        IF v_Aux!=0 THEN
		  SELECT m.DOCUMENTNO, m.DATETRX, AD_COLUMN_IDENTIFIER_STD('C_Debt_Payment',TO_CHAR(ml.C_DEBT_PAYMENT_ID))
		  INTO v_documentno_Dp_Management, v_Datetrx, v_column_identifier
		  FROM C_DP_ManagementLine ml,
          C_DP_Management m
		  WHERE ml.C_DP_Management_ID=m.C_DP_Management_ID
		  AND ml.C_DP_ManagementLine_Id = v_Dp_Managementline_Id;
          RAISE_APPLICATION_ERROR(-20000, '@Debtpayment@'||v_column_identifier||' '||'@DPDebtPaymentManaged@'||v_documentno_Dp_Management||' '||'@Bydate@'||v_Datetrx) ;
        END IF;
      END IF;--FINISH_PROCESS
      IF(NOT FINISH_PROCESS) THEN
        SELECT COUNT(*)
        INTO v_Aux
        FROM C_SETTLEMENT
        WHERE POSTED='Y'
          AND C_SETTLEMENT_ID=v_Record_ID;
        --Direct accounting settlement verification is not necessary because it's controlled in the previous restriction
        IF v_Aux<>0 THEN
          RAISE_APPLICATION_ERROR(-20000, '@SettlementDocumentPosted@') ;
        ELSE
          UPDATE C_SETTLEMENT
            SET Processed='N',
            UPDATED=now(),
            UPDATEDBY=v_AD_User_ID
          WHERE C_Settlement_ID=v_Record_ID;
          UPDATE C_DEBT_PAYMENT
            SET Cancel_Processed='N',
            UPDATED=now(),
            UPDATEDBY=v_AD_User_ID
          WHERE C_Settlement_Cancel_ID=v_Record_ID;
          UPDATE C_DEBT_PAYMENT
            SET Generate_Processed='N',
            isValid='N',
            UPDATED=now(),
            UPDATEDBY=v_AD_User_ID
          WHERE C_Settlement_Generate_ID=v_Record_ID;
          IF v_IsGenerated='N' THEN
            --Delete cashline generated from manual settlement with payed dps
            DELETE
            FROM C_CASHLINE
            WHERE C_CASHLINE.C_DEBT_PAYMENT_ID IN
              (SELECT C_DEBT_PAYMENT_ID
              FROM C_DEBT_PAYMENT
              WHERE C_SETTLEMENT_CANCEL_ID=v_Record_ID
                OR C_SETTLEMENT_GENERATE_ID=v_Record_ID
                AND IsPaid='Y'
                AND PaymentRule IN('C', 'B')
              )
              ;
          END IF;
		  v_Message:='@UnProcessedSettlement@';
        END IF;
      END IF;--FINISH_PROCESS
      FINISH_PROCESS:=true;
    END IF;
    IF(NOT FINISH_PROCESS) THEN
      /*
      *  Checking Restrictions
      */
      v_ResultStr:='CheckingRestrictions - C_DEBT_PAYMENT ORG IS IN C_BPARTNER ORG TREE';
      SELECT COUNT(*), AD_COLUMN_IDENTIFIER_STD ('C_Debt_Payment', TO_CHAR(MAX(c.C_Debt_Payment_Id)))
      INTO v_Aux, v_column_identifier
      FROM C_DEBT_PAYMENT c,
        C_BPARTNER bp
      WHERE(c.C_SETTLEMENT_CANCEL_ID=v_Record_ID
        OR c.C_SETTLEMENT_GENERATE_ID=v_Record_ID)
        AND c.C_BPARTNER_ID=bp.C_BPARTNER_ID
        AND Ad_Isorgincluded(c.AD_ORG_ID, bp.AD_ORG_ID, bp.AD_CLIENT_ID)=-1;
      IF v_Aux>0 THEN
        RAISE_APPLICATION_ERROR(-20000, '@OrgDebtpayment@'||v_column_identifier||' '||'@OrgdifferentBpartner@') ;
      END IF;
    END IF;--FINISH_PROCESS

  IF(NOT FINISH_PROCESS) THEN
      /*
      *  Checking Restrictions
      */
      v_ResultStr:='CheckingRestrictions - C_DEBT_PAYMENT ORG IS IN C_BPARTNER ORG TREE';
      SELECT COUNT(*)
      INTO v_Aux
      FROM C_SETTLEMENT S,
        C_DocType
      WHERE C_DocType.DocBaseType IN ('STT','STM')
   AND AD_ISORGINCLUDED(S.AD_Org_ID,C_DocType.AD_Org_ID, S.AD_Client_ID) <> -1
   AND S.C_SETTLEMENT_ID = v_Record_ID
   AND S.C_DOCTYPE_ID = C_DocType.C_DOCTYPE_ID;
      IF v_Aux=0 THEN
        RAISE_APPLICATION_ERROR(-20000, '@NotCorrectOrgDoctypeSettlement@') ;
      END IF;
    END IF;--FINISH_PROCESS


    IF(NOT FINISH_PROCESS) THEN
      v_ResultStr:='CheckingRestrictions - C_DEBT_PAYMENT ORG IS IN C_SETTLEMENT ORG TREE';
      SELECT COUNT(*), AD_COLUMN_IDENTIFIER_STD ('C_Debt_Payment', TO_CHAR(MAX(c.C_Debt_Payment_Id)))
      INTO v_Aux, v_column_identifier
      FROM C_DEBT_PAYMENT c,
        C_SETTLEMENT s
      WHERE(c.C_SETTLEMENT_CANCEL_ID=v_Record_ID
        OR c.C_SETTLEMENT_GENERATE_ID=v_Record_ID)
        AND s.C_SETTLEMENT_ID=v_Record_ID
        AND Ad_Isorgincluded(c.AD_ORG_ID, s.AD_ORG_ID, s.AD_CLIENT_ID)=-1;
      IF v_Aux>0 THEN
        RAISE_APPLICATION_ERROR(-20000, '@OrgDebtpayment@'||v_column_identifier||' '||'@OrgdifferentSettlement@') ;
      END IF;
    END IF;--FINISH_PROCESS
	--To be fixed o deprecated. It should be imposible to do is
    IF(NOT FINISH_PROCESS) THEN
      SELECT COUNT(*)
      INTO v_Aux
      FROM C_DEBT_PAYMENT p
      WHERE p.C_Settlement_Cancel_ID=v_Record_ID
        AND C_Debt_Payment_Status(p.C_SETTLEMENT_CANCEL_ID, p.Cancel_Processed, p.Generate_Processed, p.IsPaid, p.IsValid, p.C_CashLine_ID, p.C_BankStatementLine_ID)<>'P';
      -- If p_PInstance_ID is null there is not need to check Debt/Payment Status
      IF((v_Aux>0) AND(p_PInstance_ID IS NOT NULL)) THEN
        RAISE_APPLICATION_ERROR(-20000, '@DebtPaymentNotPending@') ;
      END IF;
	  --Until here to be deprecated
    END IF;--FINISH_PROCESS
    IF(NOT FINISH_PROCESS) THEN
      SELECT count(*), MAX(ml.C_DP_ManagementLine_Id)
        INTO v_Aux, v_Dp_Managementline_Id
      FROM C_DP_ManagementLine ml,
        C_DP_Management m,
        C_Debt_Payment dp
      WHERE ml.C_DP_Management_ID=m.C_DP_Management_ID
        AND ml.C_Debt_Payment_ID=dp.C_Debt_Payment_ID
        AND dp.C_Settlement_Cancel_ID=v_Record_ID
        AND m.processed='Y'
        AND m.DateAcct>v_DateAcct;
      if v_Aux!=0 then
	  	SELECT m.DOCUMENTNO, AD_COLUMN_IDENTIFIER_STD ('C_Debt_Payment', TO_CHAR(ml.C_Debt_Payment_Id))
		INTO v_documentno_Dp_Management, v_column_identifier
		FROM C_DP_ManagementLine ml,
        C_DP_Management m
        WHERE ml.C_DP_Management_ID=m.C_DP_Management_ID
        AND ml.C_DP_Managementline_ID=v_Dp_Managementline_Id;
        RAISE_APPLICATION_ERROR(-20000, '@Debtpayment@'||v_column_identifier||' '||'@DPDebtPaymentManaged@'||v_documentno_Dp_Management||' '||'@DPAccountdatelaterSettlementdate@') ;
      end if;
    END IF;--FINISH_PROCESS
    IF(NOT FINISH_PROCESS) THEN
      v_ResultStr:='CheckingAmounts';
      --Calculating the non-paid amount to cancel
      SELECT COALESCE(SUM(C_Currency_Round(  C_Currency_Convert((Amount-WriteOffAmt), C_Currency_ID, v_Currency, v_Date, NULL, v_AD_Client_ID, v_AD_Org_ID), v_Currency, NULL)), 0),
      COALESCE(SUM(C_Currency_Round(  C_Currency_Convert((coalesce(WithHoldingAmount,0)), C_Currency_ID, v_Currency, v_Date, NULL, v_AD_Client_ID, v_AD_Org_ID), v_Currency, NULL)), 0)
      INTO v_CanceledNotChargeAmt,v_CanceledNotChargeAmt_WH
      FROM C_Debt_Payment_V
      WHERE C_Settlement_Cancel_ID=v_Record_ID
        AND isActive='Y'
        AND isPaid='N';
      --Calculating the generated amount
      SELECT COALESCE(SUM(C_Currency_Round(  C_Currency_Convert(Amount, C_Currency_ID, v_Currency, v_Date, NULL, v_AD_Client_ID, v_AD_Org_ID), v_Currency, NULL)), 0),
      COALESCE(SUM(C_Currency_Round(  C_Currency_Convert(coalesce(WithHoldingAmount,0), C_Currency_ID, v_Currency, v_Date, NULL, v_AD_Client_ID, v_AD_Org_ID), v_Currency, NULL)), 0) 
      INTO v_GeneratedAmt,v_GeneratedAmt_WH
      FROM C_Debt_Payment_V
      WHERE C_Settlement_Generate_ID=v_Record_ID
        AND isActive='Y'
        AND isManual='N';
      --Calculating the applied amount
      SELECT COALESCE(SUM(C_Currency_Round(  C_Currency_Convert((Amount - WriteOffAmt), C_Currency_ID, v_Currency, v_Date, NULL, v_AD_Client_ID, v_AD_Org_ID), v_Currency, NULL)), 0),
      COALESCE(SUM(C_Currency_Round(  C_Currency_Convert((coalesce(WithHoldingAmount,0) ), C_Currency_ID, v_Currency, v_Date, NULL, v_AD_Client_ID, v_AD_Org_ID), v_Currency, NULL)), 0)
      INTO v_ChargedAmt,v_ChargedAmt_WH
      FROM C_Debt_Payment_V
      WHERE(C_Settlement_Cancel_ID=v_Record_ID
        OR C_Settlement_Generate_ID=v_Record_ID)
        AND isActive='Y'
        AND isPaid='Y';
      v_ResultStr:='UpdatingSettlementAmounts';
      UPDATE C_SETTLEMENT
        SET Updated=now(),
        UpdatedBy=v_AD_User_ID,
        CanceledNotChargeAmt=v_CanceledNotChargeAmt,
        GeneratedAmt=v_GeneratedAmt,
        ChargedAmt=v_ChargedAmt
      WHERE C_Settlement_ID=v_Record_ID;
      IF(v_CanceledNotChargeAmt<>v_GeneratedAmt) THEN
        RAISE_APPLICATION_ERROR(-20000, '@SettlementNotMatch@') ;
      END IF;
      IF(v_CanceledNotChargeAmt_WH<>v_GeneratedAmt_WH) THEN
        RAISE_APPLICATION_ERROR(-20000, '@SettlementWH_NotMatch@') ;
      END IF;
    END IF;--FINISH_PROCESS
    IF(NOT FINISH_PROCESS) THEN
      v_ResultStr:='UpdatingAmounts';
      UPDATE C_DEBT_PAYMENT
        SET GLItemAmt=
        ( SELECT COALESCE(SUM(cb.AmountCredit - cb.AmountDebit), 0)
        FROM C_DEBT_PAYMENT_BALANCING cb
        WHERE cb.C_Debt_Payment_ID=C_DEBT_PAYMENT.C_Debt_Payment_ID
        )
      WHERE C_Settlement_Generate_ID=v_Record_ID
        AND isManual='Y';
      v_ResultStr:='CheckingAmounts';
      --Calculating the the amount of manual debt-payment items
      SELECT COUNT(*),
        MIN(c.C_DEBT_PAYMENT_ID)
      INTO v_Aux,
        v_Debt_Payment_ID
      FROM C_Debt_Payment_V c
      WHERE c.C_Settlement_Generate_ID=v_Record_ID
        AND c.isManual='Y'
        AND c.Amount<>c.GLItemAmt;
      IF(v_Aux>0) THEN
        SELECT Ad_Column_Identifier_Std('C_Debt_Payment', to_char(v_Debt_Payment_ID))
        INTO v_column_identifier
        FROM DUAL;
        RAISE_APPLICATION_ERROR(-20000, '@AmountDebtpayment@'||v_column_identifier||' '||'@SettlementmanualNotMatch@') ;
      END IF;
    END IF;--FINISH_PROCESS
    IF(NOT FINISH_PROCESS) THEN
      v_ResultStr:='UpdatingCancelLines';
      UPDATE C_DEBT_PAYMENT
        SET Updated=now(),
        UpdatedBy=v_AD_User_ID,
        Cancel_Processed='Y'
      WHERE isActive='Y'
        AND C_Settlement_Cancel_ID=v_Record_ID;
      v_ResultStr:='UpdatingGenerateLines';
      UPDATE C_DEBT_PAYMENT
        SET Updated=now(),
        UpdatedBy=v_AD_User_ID,
        Generate_Processed='Y',
        isValid='Y'
      WHERE isActive='Y'
        AND C_Settlement_Generate_ID=v_Record_ID;
      v_ResultStr:='UpdatingSOCreditUsed';
      DECLARE
      TYPE RECORD IS REF CURSOR;
        Cur_Debts RECORD;
      BEGIN
        FOR Cur_Debts IN
          (SELECT DISTINCT C_BPartner_ID
          FROM C_DEBT_PAYMENT
          WHERE C_Settlement_Cancel_ID=v_Record_ID
            OR C_Settlement_Generate_ID=v_Record_ID
          )
        LOOP
          C_BP_SOCREDITUSED_REFRESH(Cur_Debts.C_BPartner_ID) ;
        END LOOP;
      END;
      v_ResultStr:='CreatingCashLines';
    END IF;--FINISH_PROCESS
    IF(NOT FINISH_PROCESS) THEN
      DECLARE
      TYPE RECORD IS REF CURSOR;
        Cur_Lines RECORD;
        p_CashBook NUMBER;
        p_Cash NUMBER;
        p_CashLine NUMBER;
        p_Line NUMBER;
        p_Amount NUMBER;
      BEGIN
        FOR Cur_Lines IN
          (SELECT dp.*,
            c.ISO_CODE,
            s.DateAcct
          FROM C_DEBT_PAYMENT dp,
            C_CURRENCY c,
            C_SETTLEMENT s
          WHERE dp.C_Settlement_Generate_ID=v_Record_ID
            AND s.C_SETTLEMENT_ID=dp.C_Settlement_Generate_ID
            AND dp.C_CURRENCY_ID=c.C_CURRENCY_ID
            AND dp.isActive='Y'
            AND dp.IsPaid='Y'
            AND dp.PaymentRule IN('C', 'B')
          )
        LOOP
          p_CashBook:=Cur_Lines.C_CashBook_ID;
          IF p_CashBook IS NULL THEN
            SELECT MAX(C_CashBook_ID)
            INTO p_CashBook
            FROM C_CASHBOOK
            WHERE AD_CLIENT_ID=v_AD_Client_ID
              AND ISACTIVE='Y'
              AND ISDEFAULT='Y';
            IF p_CashBook IS NULL THEN
              RAISE_APPLICATION_ERROR(-20600, 'No default cash book') ;
            END IF;
          END IF;
          IF(NOT FINISH_PROCESS) THEN
            SELECT MAX(C.C_CASH_ID)
            INTO p_Cash
            FROM C_CASH C
            WHERE C.C_CASHBOOK_ID=p_CashBook
              AND C.DATEACCT=Cur_Lines.DateAcct
              AND C.PROCESSED='N';
            SELECT C_CURRENCY.ISO_CODE
            INTO v_CashBook_ISO_Code
            FROM C_CASHBOOK,
              C_CURRENCY
            WHERE C_CASHBOOK.C_CURRENCY_ID=C_CURRENCY.C_CURRENCY_ID
              AND C_CASHBOOK_ID=p_CashBook;
            IF(p_Cash IS NULL) THEN
              v_ResultStr:='Creating C_Cash';
              Ad_Sequence_Next('C_Cash', v_AD_Org_ID, p_Cash) ;
              INSERT
              INTO C_CASH
                (
                  C_Cash_ID, AD_Client_ID, AD_Org_ID, IsActive,
                  Created, CreatedBy, Updated, UpdatedBy,
                  C_CashBook_ID, NAME, StatementDate, DateAcct,
                  BeginningBalance, EndingBalance, StatementDifference, Processing,
                  Processed, Posted
                )
                VALUES
                (
                  p_Cash, v_AD_Client_ID, v_AD_Org_ID, 'Y',
                  now(), v_AD_User_ID, now(), v_AD_User_ID,
                  p_CashBook, (TO_CHAR(Cur_Lines.DateAcct, 'YYYY-MM-DD') || ' ' || v_CashBook_ISO_Code), v_Date, v_Date,
                  0, 0, 0, 'N',
                   'N', 'N'
                )
                ;
            END IF; --p_Cash IS NULL
            v_ResultStr:='Creating C_CashLine';
            Ad_Sequence_Next('C_CashLine', v_AD_Org_ID, p_CashLine) ;
            SELECT COALESCE(MAX(LINE), 0) + 10
            INTO p_Line
            FROM C_CASHLINE
            WHERE C_CASH_ID=p_Cash;
            p_Amount:=Cur_Lines.Amount - Cur_Lines.WriteOffAmt;
            IF Cur_Lines.isReceipt='N' THEN
              p_Amount:=p_Amount * -1;
            END IF;
            INSERT
            INTO C_CASHLINE
              (
                C_CashLine_ID, AD_Client_ID, AD_Org_ID, IsActive,
                Created, CreatedBy, Updated, UpdatedBy,
                C_Cash_ID, C_Debt_Payment_ID, Line, Description,
                Amount, CashType, C_Currency_ID, DiscountAmt,
                WriteOffAmt, IsGenerated
              )
              VALUES
              (
                p_CashLine, v_AD_Client_ID, v_AD_Org_ID, 'Y',
                now(), v_AD_User_ID, now(), v_AD_User_ID,
                p_Cash, Cur_Lines.C_Debt_Payment_ID, p_Line, Cur_Lines.Description,
                p_Amount, 'P', Cur_Lines.C_Currency_ID, 0,
                0, 'Y'
              )
              ;
          END IF;--FINISH_PROCESS
        END LOOP;
      END;
    END IF;--FINISH_PROCESS
    IF(NOT FINISH_PROCESS) THEN
      v_ResultStr:='UpdatingSettlement';
      UPDATE C_SETTLEMENT
        SET Updated=now(),
        UpdatedBy=v_AD_User_ID,
        Processed='Y'
      WHERE C_Settlement_ID=v_Record_ID;
    END IF;--FINISH_PROCESS
    --<<FINISH_PROCESS>>
    --  Update AD_PInstance
    IF(p_PInstance_ID IS NOT NULL) THEN
      DBMS_OUTPUT.PUT_LINE('Updating PInstance - Finished ' || v_Message) ;
      AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'N', v_Result, v_Message) ;
      DBMS_OUTPUT.PUT_LINE('--<<C_Settlement_Post finished>> ' || v_Message) ;
    END IF;
    RETURN;
  END; --BODY
EXCEPTION
WHEN OTHERS THEN
  v_ResultStr:= '@ERROR=' || SQLERRM;
  DBMS_OUTPUT.PUT_LINE(v_ResultStr) ;
  IF(p_PInstance_ID IS NOT NULL) THEN
    ROLLBACK;
    AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'N', 0, v_ResultStr) ;
  ELSE
    RAISE;
  END IF;
  RETURN;
END C_SETTLEMENT_POST
]]></body>
    </function>
  </database>