src-db/database/model/functions/C_INVOICE_POST.xml
author Sivaraman Rajagopal <sivaraman.rajagopal@openbravo.com>
Wed, 07 Jul 2010 16:58:42 +0530
changeset 7819 110640fbe62b
parent 7808 801436f99c13
child 7929 acce63739f67
permissions -rw-r--r--
Fixes issue 12793: Sales invoices of a business partner with a withholding associated creates payments with incorrect amount

C_INVOICE_POST is responsible to complete both purchase and sales invoices. There, It just subtracts the withholding from the net amount without checking the document type if corresponding Business Partner is associated with any Withholding.
As a fix, an IF clause has been added to take Withholding into account only if document type is ''PURCHASE\" otherwise 0 amount will be subtracted.
carlos@0
     1
<?xml version="1.0"?>
adrian@94
     2
  <database name="FUNCTION C_INVOICE_POST">
adrian@94
     3
    <function name="C_INVOICE_POST" type="NULL">
juanpablo@1605
     4
      <parameter name="p_pinstance_id" type="VARCHAR" mode="in">
antonio@735
     5
        <default/>
antonio@735
     6
      </parameter>
juanpablo@1605
     7
      <parameter name="p_invoice_id" type="VARCHAR" mode="in">
antonio@735
     8
        <default/>
antonio@735
     9
      </parameter>
gorkaion@239
    10
      <body><![CDATA[/*************************************************************************
juanpablo@771
    11
  * The contents of this file are subject to the Compiere Public
juanpablo@771
    12
  * License 1.1 ("License"); You may not use this file except in
juanpablo@771
    13
  * compliance with the License. You may obtain a copy of the License in
juanpablo@771
    14
  * the legal folder of your Openbravo installation.
carlos@0
    15
  * Software distributed under the License is distributed on an
carlos@0
    16
  * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
carlos@0
    17
  * implied. See the License for the specific language governing rights
carlos@0
    18
  * and limitations under the License.
juanpablo@778
    19
  * The Original Code is  Compiere  ERP &  Business Solution
juanpablo@771
    20
  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
carlos@0
    21
  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke,
carlos@0
    22
  * parts created by ComPiere are Copyright (C) ComPiere, Inc.;
carlos@0
    23
  * All Rights Reserved.
ggi@6701
    24
  * Contributor(s): Openbravo SLU
ggi@6701
    25
  * Contributions are Copyright (C) 2001-2010 Openbravo, S.L.U.
juanpablo@771
    26
  *
juanpablo@771
    27
  * Specifically, this derivative work is based upon the following Compiere
juanpablo@771
    28
  * file and version.
carlos@0
    29
  *************************************************************************
carlos@0
    30
  * $Id: C_Invoice_Post.sql,v 1.32 2003/07/22 05:41:27 jjanke Exp $
carlos@0
    31
  ***
carlos@0
    32
  * Title:  Post single Invoice
carlos@0
    33
  * Description:
carlos@0
    34
  *  Actions: COmplete, APprove, Reverse Correction, Void
carlos@0
    35
  *
carlos@0
    36
  * OpenItem Amount:
carlos@0
    37
  *  - C_BPartner.SO_CreditUsed is increased
gorkaion@7647
    38
  *  - if C_CashLine entry is created
carlos@0
    39
  *  - C_Cash_Post creates C_Allocation
gorkaion@7647
    40
  *  - C_Allocation_Trg decreases C_BPartner.SO_CreditUsed
carlos@0
    41
  *
carlos@0
    42
  ************************************************************************/
carlos@0
    43
  -- Logistice
carlos@0
    44
  v_ResultStr VARCHAR2(2000):='';
carlos@0
    45
  v_Message VARCHAR2(2000):='';
juanpablo@1605
    46
  v_Record_ID VARCHAR2(32);
carlos@0
    47
  v_Result NUMBER:=1; -- Success
harikrishnan@7678
    48
  v_totalqty NUMBER:=0; 
carlos@0
    49
  -- Parameter
carlos@0
    50
  TYPE RECORD IS REF CURSOR;
gorkaion@7647
    51
  Cur_Parameter RECORD;
gorkaion@7647
    52
  Cur_line RECORD;
gorkaion@7647
    53
  Cur_InvoiceLine RECORD;
gorkaion@7647
    54
  Cur_Discount RECORD;
gorkaion@7647
    55
  Cur_CInvoiceDiscount RECORD;
gorkaion@7647
    56
  Cur_TaxDiscount RECORD;
gorkaion@7647
    57
  Cur_ReactivateInvoiceLine RECORD;
gorkaion@7647
    58
  Cur_LastContact RECORD;
harikrishnan@7678
    59
  Cur_lineqty RECORD;
carlos@0
    60
gorkaion@7647
    61
  -- Record Info
gorkaion@7647
    62
  v_Client_ID VARCHAR2(32);
gorkaion@7647
    63
  v_User_ID VARCHAR2(32);
gorkaion@7647
    64
  v_Org_ID VARCHAR2(32);
gorkaion@7647
    65
  v_UpdatedBy C_INVOICE.UpdatedBy%TYPE;
gorkaion@7647
    66
  v_Processing C_INVOICE.Processing%TYPE;
gorkaion@7647
    67
  v_Processed C_INVOICE.Processed%TYPE;
gorkaion@7647
    68
  v_DocAction C_INVOICE.DocAction%TYPE;
gorkaion@7647
    69
  v_DocStatus C_INVOICE.DocStatus%TYPE;
gorkaion@7647
    70
  v_DoctypeReversed_ID VARCHAR2(32);
gorkaion@7647
    71
  v_DocType_ID VARCHAR2(32);
gorkaion@7647
    72
  v_DocTypeTarget_ID VARCHAR2(32);
gorkaion@7647
    73
  v_PaymentRule C_INVOICE.PaymentRule%TYPE;
gorkaion@7647
    74
  v_PaymentTerm C_INVOICE.C_PaymentTerm_ID%TYPE;
gorkaion@7647
    75
  v_Order_ID VARCHAR2(32);
gorkaion@7647
    76
  v_DateAcct DATE;
gorkaion@7647
    77
  v_DateInvoiced DATE;
gorkaion@7647
    78
  v_DocumentNo C_INVOICE.DocumentNo%TYPE;
gorkaion@7647
    79
  v_BPartner_ID VARCHAR2(32);
gorkaion@7647
    80
  v_BPartner_User_ID VARCHAR2(32);
gorkaion@7647
    81
  v_IsSOTrx C_INVOICE.IsSOTrx%TYPE;
gorkaion@7647
    82
  v_Posted C_INVOICE.Posted%TYPE;
carlos@0
    83
  --Added by P.SAROBE
carlos@0
    84
  v_documentno_Settlement VARCHAR2(40);
carlos@0
    85
  v_dateSettlement DATE;
carlos@0
    86
  v_Cancel_Processed CHAR(1);
carlos@0
    87
  v_nameBankstatement VARCHAR2 (60);
carlos@0
    88
  v_dateBankstatement DATE;
carlos@0
    89
  v_nameCash VARCHAR2 (60);
carlos@0
    90
  v_dateCash DATE;
juanpablo@1605
    91
  v_Bankstatementline_ID VARCHAR2(32);
juanpablo@1605
    92
  v_Debtpayment_ID VARCHAR2(32);
juanpablo@1605
    93
  v_CashLine_ID VARCHAR2(32);
carlos@0
    94
  v_ispaid CHAR(1);
juanpablo@1605
    95
  v_Settlement_Cancel_ID VARCHAR2(32);
carlos@0
    96
  --Finish added by P.Sarobe
gorkaion@7647
    97
  --
gorkaion@7647
    98
  v_GrandTotal NUMBER:=0;
gorkaion@7647
    99
  v_TotalLines NUMBER:=0;
gorkaion@7647
   100
  v_Currency_ID VARCHAR2(32);
gorkaion@7647
   101
  v_Multiplier NUMBER:=1;
gorkaion@7647
   102
  v_paymentcheck NUMBER;
gorkaion@7647
   103
  --
gorkaion@7647
   104
  v_RInvoice_ID VARCHAR2(32);
gorkaion@7647
   105
  v_RDocumentNo C_INVOICE.DocumentNo%TYPE;
gorkaion@7647
   106
  v_NextNo VARCHAR2(32);
gorkaion@7647
   107
  v_count NUMBER;
gorkaion@7647
   108
  v_POReference NVARCHAR2(40) ;
gorkaion@7647
   109
  --
gorkaion@7647
   110
  v_SettlementDocType_ID VARCHAR2(32) ;
gorkaion@7647
   111
  v_SDocumentNo C_SETTLEMENT.DocumentNo%TYPE;
gorkaion@7647
   112
  v_settlementID varchar2(32):=NULL;
gorkaion@7647
   113
  --
gorkaion@7647
   114
  v_FirstSales C_BPARTNER.FirstSale%TYPE;
gorkaion@7647
   115
  v_REInOutStatus M_INOUT.DocStatus%TYPE;
gorkaion@7647
   116
  v_REDateInvoiced DATE;
gorkaion@7647
   117
  v_REtotalQtyInvoiced NUMBER:=0;
gorkaion@7647
   118
  v_REdeliveredQty NUMBER:=0;
gorkaion@7647
   119
  --
gorkaion@7647
   120
  v_CumDiscount NUMBER;
gorkaion@7647
   121
  v_OldCumDiscount NUMBER;
gorkaion@7647
   122
  v_InvoiceLineSeqNo NUMBER;
gorkaion@7647
   123
  v_InvoiceLine VARCHAR2(32);
gorkaion@7647
   124
  v_Discount NUMBER;
gorkaion@7647
   125
  v_Line NUMBER;
gorkaion@7647
   126
  v_InvoiceDiscount NUMBER;
gorkaion@7647
   127
  v_C_Project_ID VARCHAR2(32);
gorkaion@7647
   128
  v_acctAmount NUMBER;
gorkaion@7647
   129
  v_partialAmount NUMBER;
gorkaion@7647
   130
  FINISH_PROCESS BOOLEAN:=FALSE;
gorkaion@7647
   131
  END_PROCESSING BOOLEAN:=FALSE;
gorkaion@7647
   132
  v_TargetDocBaseType C_DOCTYPE.DocBaseType%TYPE;
gorkaion@7647
   133
  v_MultiplierARC NUMBER:=1;
gorkaion@7647
   134
  v_is_included NUMBER:=0;
gorkaion@7647
   135
  v_available_period NUMBER:=0;
gorkaion@7647
   136
  v_is_ready AD_Org.IsReady%TYPE;
gorkaion@7647
   137
  v_is_tr_allow AD_OrgType.IsTransactionsAllowed%TYPE;
gorkaion@7647
   138
  v_isacctle AD_OrgType.IsAcctLegalEntity%TYPE;
gorkaion@7647
   139
  v_org_bule_id AD_Org.AD_Org_ID%TYPE;
gorkaion@7647
   140
  
gorkaion@7647
   141
  v_PeriodStartDate DATE;
gorkaion@7647
   142
  v_PeriodEndDate DATE;
gorkaion@7647
   143
  v_DocNo_Org_ID AD_Sequence.AD_Org_ID%TYPE;
gorkaion@7647
   144
  withholdamount NUMBER(10,2);
gorkaion@7647
   145
  cWithHoldId varchar2(32);
harikrishnan@7808
   146
  Cur_InvoiceNetLine RECORD;
rafael@5358
   147
    
gorkaion@7647
   148
BEGIN
gorkaion@7647
   149
  IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@7647
   150
    --  Update AD_PInstance
gorkaion@7647
   151
    DBMS_OUTPUT.PUT_LINE('Updating PInstance - Processing ' || p_PInstance_ID) ;
gorkaion@7647
   152
    v_ResultStr:='PInstanceNotFound';
gorkaion@7647
   153
    AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'Y', NULL, NULL) ;
gorkaion@7647
   154
    -- Get Parameters
gorkaion@7647
   155
    v_ResultStr:='ReadingParameters';
gorkaion@7647
   156
    FOR Cur_Parameter IN
gorkaion@7647
   157
      (SELECT i.Record_ID,
gorkaion@7647
   158
        i.AD_User_ID,
gorkaion@7647
   159
        p.ParameterName,
gorkaion@7647
   160
        p.P_String,
gorkaion@7647
   161
        p.P_Number,
gorkaion@7647
   162
        p.P_Date
gorkaion@7647
   163
      FROM AD_PINSTANCE i
gorkaion@7647
   164
      LEFT JOIN AD_PINSTANCE_PARA p
gorkaion@7647
   165
        ON i.AD_PInstance_ID=p.AD_PInstance_ID
gorkaion@7647
   166
      WHERE i.AD_PInstance_ID=p_PInstance_ID
gorkaion@7647
   167
      ORDER BY p.SeqNo
gorkaion@7647
   168
      )
gorkaion@7647
   169
    LOOP
gorkaion@7647
   170
      v_Record_ID:=Cur_Parameter.Record_ID;
gorkaion@7647
   171
      v_User_ID:=Cur_Parameter.AD_User_ID;
gorkaion@7647
   172
    END LOOP; -- Get Parameter
gorkaion@7647
   173
    DBMS_OUTPUT.PUT_LINE('  v_Record_ID=' || v_Record_ID) ;
gorkaion@7647
   174
  ELSE
gorkaion@7647
   175
    DBMS_OUTPUT.PUT_LINE('--<<C_Invoive_Post>>') ;
gorkaion@7647
   176
    v_Record_ID:=p_Invoice_ID;
gorkaion@7647
   177
  END IF;
gorkaion@7647
   178
BEGIN --BODY
carlos@0
   179
gorkaion@7647
   180
  /*Invoiceline acct dimension*/
gorkaion@7647
   181
  SELECT C_INVOICE.ISSOTRX INTO v_IsSOTrx
gorkaion@7647
   182
  FROM C_INVOICE
gorkaion@7647
   183
  WHERE C_INVOICE_ID = v_Record_ID;
gorkaion@7647
   184
  IF (v_IsSOTrx = 'N') THEN
gorkaion@7647
   185
    FOR Cur_line IN
gorkaion@7647
   186
      (SELECT C_INVOICELINE.C_InvoiceLine_ID,
gorkaion@7647
   187
       C_INVOICELINE.LinenetAmt
gorkaion@7647
   188
       FROM C_INVOICELINE
gorkaion@7647
   189
       WHERE C_Invoice_ID = v_Record_ID
gorkaion@7647
   190
      )
gorkaion@7647
   191
    LOOP
gorkaion@7647
   192
      SELECT SUM(Amt) INTO v_acctAmount
gorkaion@7647
   193
      FROM C_INVOICELINE_ACCTDIMENSION
gorkaion@7647
   194
      WHERE C_InvoiceLine_ID = Cur_line.C_InvoiceLine_ID;
gorkaion@7647
   195
      IF (v_acctAmount <> Cur_line.LinenetAmt) THEN
gorkaion@7647
   196
        v_Message:='@QuantitiesNotMatch@';
gorkaion@7647
   197
        RAISE_APPLICATION_ERROR(-20000, '@QuantitiesNotMatch@') ;
gorkaion@7647
   198
      END IF;
gorkaion@7647
   199
    END LOOP;
carlos@0
   200
  END IF;
gorkaion@7647
   201
  /**
gorkaion@7647
   202
   * Read Invoice
gorkaion@7647
   203
   */
gorkaion@7647
   204
  v_ResultStr:='ReadingInvoice';
gorkaion@7647
   205
  SELECT Processing, Processed, DocAction, DocStatus,
asier@799
   206
      C_DocType_ID, C_DocTypeTarget_ID,
carlos@0
   207
      PaymentRule, C_PaymentTerm_ID, DateAcct, DateInvoiced,
carlos@0
   208
      AD_Client_ID, AD_Org_ID, UpdatedBy, DocumentNo,
carlos@0
   209
      C_Order_ID, IsSOTrx, C_BPartner_ID, AD_User_ID,
gorkaion@7647
   210
      C_Currency_ID, POReference, Posted,
eduardo@717
   211
      c_Project_Id, C_WithHolding_ID
gorkaion@7647
   212
  INTO v_Processing, v_Processed, v_DocAction, v_DocStatus,
asier@799
   213
      v_DocType_ID, v_DocTypeTarget_ID,
carlos@0
   214
      v_PaymentRule, v_PaymentTerm, v_DateAcct, v_DateInvoiced,
carlos@0
   215
      v_Client_ID, v_Org_ID, v_UpdatedBy, v_DocumentNo,
carlos@0
   216
      v_Order_ID, v_IsSOTrx, v_BPartner_ID, v_BPartner_User_ID,
gorkaion@7647
   217
      v_Currency_ID, v_POReference, v_Posted,
eduardo@717
   218
      v_C_Project_Id, cWithHoldID
gorkaion@7647
   219
  FROM C_INVOICE
gorkaion@7647
   220
  WHERE C_Invoice_ID=v_Record_ID FOR UPDATE;
gorkaion@7647
   221
  DBMS_OUTPUT.PUT_LINE('Invoice_ID=' || v_Record_ID ||', DocAction=' || v_DocAction || ', DocStatus=' || v_DocStatus || ', DocType_ID=' || v_DocType_ID || ', DocTypeTarget_ID=' || v_DocTypeTarget_ID) ;
gorkaion@7647
   222
  /**
gorkaion@7647
   223
   * Invoice Voided, Closed, or Reversed - No Action
gorkaion@7647
   224
   */
gorkaion@7647
   225
  IF (v_User_ID IS NOT NULL) THEN
gorkaion@7647
   226
    v_UpdatedBy:=v_User_ID;
gorkaion@7647
   227
  END IF;
gorkaion@7647
   228
  IF (v_DocStatus IN('VO', 'CL', 'RE')) THEN
gorkaion@7647
   229
    RAISE_APPLICATION_ERROR(-20000, '@AlreadyPosted@');
gorkaion@7647
   230
  END IF;
gorkaion@7647
   231
  --Allow to complete an invoice only in these cases:
gorkaion@7647
   232
  --* There are invoice lines
gorkaion@7647
   233
  --* There are tax lines
gorkaion@7647
   234
  --* There are both invoice and tax lines 
gorkaion@7647
   235
  IF (v_DocStatus='DR' AND v_DocAction='CO') THEN
gorkaion@7647
   236
    SELECT COUNT(*) INTO v_count
carlos@0
   237
    FROM C_INVOICE
gorkaion@7647
   238
    WHERE C_INVOICE_ID=v_Record_ID 
gorkaion@7647
   239
      AND (EXISTS (SELECT 1
gorkaion@7647
   240
                   FROM C_INVOICELINE
gorkaion@7647
   241
                   WHERE C_INVOICE_ID=v_Record_ID)
gorkaion@7647
   242
           OR EXISTS (SELECT 1
gorkaion@7647
   243
                      FROM C_INVOICETAX
gorkaion@7647
   244
                      WHERE C_INVOICE_ID=v_Record_ID));
gorkaion@7647
   245
gorkaion@7647
   246
    IF (v_count=0) THEN
gorkaion@7647
   247
      RAISE_APPLICATION_ERROR(-20000, '@InvoicesNeedLines@');
gorkaion@7647
   248
    END IF;
gorkaion@7647
   249
    /*
gorkaion@7647
   250
     * Avoids repeating the same documentno for the same organization tree within the same fiscal year
gorkaion@7647
   251
     */
gorkaion@7647
   252
    SELECT COUNT(*) INTO v_count
gorkaion@7647
   253
    FROM (SELECT Y.C_CALENDAR_ID, Y.C_YEAR_ID,
gorkaion@7647
   254
              MIN(P.STARTDATE) AS PERIODSTARTDATE, MAX(P.ENDDATE) AS PERIODENDDATE
gorkaion@7647
   255
          FROM C_YEAR Y, C_PERIOD P
gorkaion@7647
   256
          WHERE Y.C_YEAR_ID = P.C_YEAR_ID
gorkaion@7647
   257
            AND Y.ISACTIVE = 'Y'
gorkaion@7647
   258
            AND P.ISACTIVE = 'Y'
gorkaion@7647
   259
            AND Y.C_CALENDAR_ID = (SELECT O.C_CALENDAR_ID 
gorkaion@7647
   260
                                   FROM AD_ORG O
gorkaion@7647
   261
                                   WHERE AD_ORG_ID = AD_ORG_GETCALENDAROWNER(v_Org_ID))
gorkaion@7647
   262
          GROUP BY Y.C_CALENDAR_ID, Y.C_YEAR_ID) A
gorkaion@7647
   263
    WHERE PERIODSTARTDATE <= v_DateInvoiced
gorkaion@7647
   264
      AND PERIODENDDATE+1 > v_DateInvoiced ;
gorkaion@7647
   265
    IF (v_count<>0) THEN
gorkaion@7647
   266
      SELECT PERIODSTARTDATE, PERIODENDDATE
gorkaion@7647
   267
        INTO v_PeriodStartDate, v_PeriodEndDate
gorkaion@7647
   268
      FROM (SELECT Y.C_CALENDAR_ID, Y.C_YEAR_ID,
gorkaion@7647
   269
                MIN(P.STARTDATE) AS PERIODSTARTDATE, MAX(P.ENDDATE) AS PERIODENDDATE
gorkaion@7647
   270
            FROM C_YEAR Y, C_PERIOD P
gorkaion@7647
   271
            WHERE Y.C_YEAR_ID = P.C_YEAR_ID
gorkaion@7647
   272
              AND Y.ISACTIVE = 'Y'
gorkaion@7647
   273
              AND P.ISACTIVE = 'Y'
gorkaion@7647
   274
              AND Y.C_CALENDAR_ID = (SELECT O.C_CALENDAR_ID 
gorkaion@7647
   275
                                     FROM AD_ORG O
gorkaion@7647
   276
                                     WHERE AD_ORG_ID = AD_ORG_GETCALENDAROWNER(v_Org_ID))
gorkaion@7647
   277
            GROUP BY Y.C_CALENDAR_ID, Y.C_YEAR_ID) A
gorkaion@7647
   278
      WHERE PERIODSTARTDATE <= v_DateInvoiced
gorkaion@7647
   279
        AND PERIODENDDATE+1 > v_DateInvoiced ;
gorkaion@7647
   280
      IF (v_PeriodStartDate IS NOT NULL AND v_PeriodEndDate IS NOT NULL) THEN
gorkaion@7647
   281
        SELECT D.AD_ORG_ID INTO v_DocNo_Org_ID
gorkaion@7647
   282
        FROM C_DOCTYPE D
gorkaion@7647
   283
        WHERE D.C_DOCTYPE_ID = v_DocTypeTarget_ID ;
gorkaion@7647
   284
        SELECT COUNT(*) INTO v_count
gorkaion@7647
   285
        FROM C_INVOICE I
gorkaion@7647
   286
        WHERE I.DOCUMENTNO = v_DocumentNo
gorkaion@7647
   287
          AND I.C_DOCTYPETARGET_ID = v_DocTypeTarget_ID
gorkaion@7647
   288
          AND I.DATEINVOICED >= v_PeriodStartDate
gorkaion@7647
   289
          AND I.DATEINVOICED < v_PeriodEndDate+1 
gorkaion@7647
   290
          AND I.C_INVOICE_ID <> v_Record_ID 
gorkaion@7647
   291
          AND AD_ISORGINCLUDED(I.AD_ORG_ID, v_DocNo_Org_ID, I.AD_CLIENT_ID) <> -1
gorkaion@7647
   292
          AND I.AD_CLIENT_ID = v_Client_ID ;
gorkaion@7647
   293
        IF (v_count<>0) THEN
gorkaion@7647
   294
          RAISE_APPLICATION_ERROR(-20000, '@DifferentDocumentNo@');
gorkaion@7647
   295
        END IF;
gorkaion@7647
   296
      END IF;
gorkaion@7647
   297
    END IF;
gorkaion@7647
   298
  END IF;
gorkaion@7647
   299
  IF (NOT FINISH_PROCESS) THEN
carlos@0
   300
    /**
gorkaion@7647
   301
     * Unlock
gorkaion@7647
   302
     */
gorkaion@7647
   303
    IF (v_DocAction='XL') THEN
gorkaion@7647
   304
      UPDATE C_INVOICE
gorkaion@7647
   305
      SET Processing='N',
carlos@0
   306
          DocAction='--',
harikrishnan@7209
   307
          Updated=now(),
harikrishnan@7209
   308
          UpdatedBy=v_UpdatedBy
gorkaion@7647
   309
      WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   310
      FINISH_PROCESS:=TRUE;
gorkaion@7647
   311
    END IF;
gorkaion@7647
   312
  END IF;--FINISH_PROCESS
gorkaion@7647
   313
  IF (NOT FINISH_PROCESS) THEN
gorkaion@7647
   314
    IF (v_Processing='Y') THEN
gorkaion@7647
   315
      RAISE_APPLICATION_ERROR(-20000, '@OtherProcessActive@');
gorkaion@7647
   316
    END IF;
gorkaion@7647
   317
  END IF;--FINISH_PROCESS
gorkaion@7647
   318
  IF (NOT FINISH_PROCESS) THEN
gorkaion@7647
   319
    /**
gorkaion@7647
   320
     * Everything done
gorkaion@7647
   321
     */
gorkaion@7647
   322
    IF (v_Processed='Y' AND v_DocAction NOT IN('RC', 'RE')) THEN
gorkaion@7647
   323
      RAISE_APPLICATION_ERROR(-20000, '@AlreadyPosted@');
gorkaion@7647
   324
    END IF;
gorkaion@7647
   325
  END IF;--FINISH_PROCESS
gorkaion@7647
   326
  --cbt taxpayment
gorkaion@7647
   327
gorkaion@7647
   328
  IF (NOT FINISH_PROCESS) THEN
gorkaion@7647
   329
    IF (v_docaction IN ('VO', 'RE', 'RC')
gorkaion@7647
   330
       AND v_docstatus IN('CO', 'CL')) THEN
gorkaion@7647
   331
      SELECT COUNT(*) INTO v_count
gorkaion@7647
   332
      FROM c_taxregisterline trl
gorkaion@7647
   333
           INNER JOIN c_invoicetax it ON trl.c_invoicetax_id = it.c_invoicetax_id
gorkaion@7647
   334
           INNER JOIN c_taxregister tr ON tr.c_taxregister_id= trl.c_taxregister_id
gorkaion@7647
   335
           INNER JOIN c_taxpayment tp ON tr.c_taxpayment_id=tp.c_taxpayment_id
gorkaion@7647
   336
      WHERE it.c_invoice_id = v_record_id
gorkaion@7647
   337
        AND tp.processed='Y';
gorkaion@7647
   338
      IF (v_count > 0) THEN
gorkaion@7647
   339
        RAISE_APPLICATION_ERROR(-20615,   '@InvoiceInTaxRegister@');
gorkaion@7647
   340
      ELSE
gorkaion@7647
   341
        DELETE FROM c_taxregisterline 
gorkaion@7647
   342
        WHERE c_taxregisterline.c_invoicetax_id IN
gorkaion@7647
   343
              (SELECT trl.c_invoicetax_id
gorkaion@7647
   344
               FROM c_taxregisterline trl
gorkaion@7647
   345
                    INNER JOIN c_invoicetax it ON trl.c_invoicetax_id = it.c_invoicetax_id
gorkaion@7647
   346
                    INNER JOIN c_taxregister tr ON tr.c_taxregister_id= trl.c_taxregister_id
gorkaion@7647
   347
                    INNER JOIN c_taxpayment tp ON tr.c_taxpayment_id=tp.c_taxpayment_id
gorkaion@7647
   348
               WHERE it.c_invoice_id = v_record_id
gorkaion@7647
   349
                 AND tp.processed='N');
carlos@0
   350
      END IF;
gorkaion@7647
   351
    END IF;
gorkaion@7647
   352
  END IF;
antonio@737
   353
gorkaion@7647
   354
  --end cbt taxpaymant
gorkaion@7647
   355
  IF (NOT FINISH_PROCESS) THEN
harikrishnan@7808
   356
  /**
harikrishnan@7808
   357
    *Update Invoice Net Unit Price to Product purchasing Plan Table
harikrishnan@7808
   358
    */
harikrishnan@7808
   359
    IF(v_isSoTrx ='N') THEN
harikrishnan@7808
   360
      FOR Cur_InvoiceNetLine IN (SELECT * FROM C_INVOICELINE WHERE C_Invoice_Id =  v_Record_ID)
harikrishnan@7808
   361
      LOOP
harikrishnan@7808
   362
          UPDATE M_PRODUCT_PO SET PriceLastInv=Cur_InvoiceNetLine.PriceActual 
harikrishnan@7808
   363
          Where C_BPARTNER_ID = v_BPartner_ID AND M_PRODUCT_ID = Cur_InvoiceNetLine.M_PRODUCT_ID
harikrishnan@7808
   364
          AND Ad_Isorgincluded(Cur_InvoiceNetLine.AD_ORG_ID,AD_ORG_ID, Cur_InvoiceNetLine.AD_Client_ID) <> -1;
harikrishnan@7808
   365
      END LOOP;
harikrishnan@7808
   366
    END IF;
gorkaion@7647
   367
    /**
gorkaion@7647
   368
     * Void if Document not processed
gorkaion@7647
   369
     */
gorkaion@7647
   370
    IF (v_DocAction='VO' AND v_DocStatus NOT IN('CO', 'RE')) THEN
gorkaion@7647
   371
      SELECT COUNT(*) INTO v_count
gorkaion@7647
   372
      FROM C_DEBT_PAYMENT
gorkaion@7647
   373
      WHERE C_Invoice_ID = v_Record_ID;
gorkaion@7647
   374
      IF (v_count>0) THEN
gorkaion@7647
   375
        RAISE_APPLICATION_ERROR(-20000, '@InvoiceWithManualDP@');
antonio@737
   376
      ELSE
gorkaion@7647
   377
        -- Reset Lines to 0
gorkaion@7647
   378
        UPDATE C_INVOICELINE
gorkaion@7647
   379
        SET QtyInvoiced=0,
harikrishnan@7209
   380
            LineNetAmt=0,
harikrishnan@7209
   381
            Updated=now(),
gorkaion@7647
   382
            UpdatedBy=v_UpdatedBy
gorkaion@7647
   383
        WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   384
gorkaion@7647
   385
        UPDATE C_INVOICE
gorkaion@7647
   386
        SET DocStatus='VO',
carlos@0
   387
            DocAction='--',
carlos@0
   388
            Processed='Y',
harikrishnan@7209
   389
            Updated=now(),
harikrishnan@7209
   390
            UpdatedBy=v_UpdatedBy
gorkaion@7647
   391
        WHERE C_Invoice_ID=v_Record_ID;
carlos@0
   392
      END IF;
gorkaion@7647
   393
      FINISH_PROCESS:=TRUE;
gorkaion@7647
   394
    END IF;
gorkaion@7647
   395
  END IF;--FINISH_PROCESS
gorkaion@7647
   396
  IF (NOT FINISH_PROCESS) THEN
gorkaion@7647
   397
    /**************************************************************************
gorkaion@7647
   398
     * Start Processing ------------------------------------------------------
gorkaion@7647
   399
     *************************************************************************/
gorkaion@7647
   400
    v_ResultStr:='LockingInvoice';
gorkaion@7647
   401
    BEGIN -- FOR COMMIT
gorkaion@7647
   402
      UPDATE C_INVOICE
gorkaion@7647
   403
      SET Processing='Y',
gorkaion@7647
   404
          Updated=now(),
gorkaion@7647
   405
          UpdatedBy=v_UpdatedBy
gorkaion@7647
   406
      WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   407
      -- Now, needs to go to END_PROCESSING to unlock
gorkaion@7647
   408
      -- This Commit must remanin due differences between PL execution in Oracle and Postgres
gorkaion@7647
   409
      IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@7647
   410
        COMMIT;
gorkaion@7647
   411
      END IF;
carlos@0
   412
      EXCEPTION WHEN OTHERS THEN RAISE NO_DATA_FOUND;
gorkaion@7647
   413
    END;--FOR  COMMIT
gorkaion@7647
   414
    BEGIN -- FOR COMMIT
carlos@0
   415
gorkaion@7647
   416
      -- Set org lines like the headear
gorkaion@7647
   417
      UPDATE C_INVOICELINE
harikrishnan@7209
   418
      SET AD_ORG_ID = (SELECT AD_ORG_ID FROM C_INVOICE WHERE C_INVOICE_ID = v_Record_ID),Updated=now(),
harikrishnan@7209
   419
          UpdatedBy=v_UpdatedBy
gorkaion@7647
   420
      WHERE C_INVOICE_ID = v_Record_ID;
carlos@0
   421
gorkaion@7647
   422
      SELECT COUNT(*) INTO v_Count
gorkaion@7647
   423
      FROM C_INVOICE C,
gorkaion@7647
   424
           C_DOCTYPE
gorkaion@7647
   425
      WHERE C_DOCTYPE.DocBaseType IN ('ARI', 'API','ARC','APC')
gorkaion@7647
   426
        AND C_DOCTYPE.IsSOTrx=C.ISSOTRX
gorkaion@7647
   427
        AND Ad_Isorgincluded(C.AD_Org_ID,C_DOCTYPE.AD_Org_ID, C.AD_Client_ID) <> -1
gorkaion@7647
   428
        AND C.C_DOCTYPETARGET_ID = C_DOCTYPE.C_DOCTYPE_ID
gorkaion@7647
   429
        AND C.C_INVOICE_ID = V_RECORD_ID;
gorkaion@7647
   430
      IF (v_Count=0) THEN
carlos@0
   431
        RAISE_APPLICATION_ERROR(-20000, '@NotCorrectOrgDoctypeInvoice@');
carlos@0
   432
      END IF;
carlos@0
   433
gorkaion@7647
   434
      /**
gorkaion@7647
   435
       * Reverse Correction requires completes invoice ========================
gorkaion@7647
   436
       */
gorkaion@7647
   437
      IF (v_DocAction='RC' AND v_DocStatus='CO') THEN
gorkaion@7647
   438
        v_ResultStr:='ReverseCorrection';
gorkaion@7647
   439
        -- Copy Invoice with reverese Quantities (or Amounts)
gorkaion@7647
   440
        v_RInvoice_ID:= get_uuid();
gorkaion@7647
   441
        SELECT COALESCE(C_DOCTYPE_REVERSED_ID, C_DOCTYPE_ID) INTO v_DoctypeReversed_ID
gorkaion@7647
   442
        FROM C_DOCTYPE
gorkaion@7647
   443
        WHERE C_DOCTYPE_ID=v_DocType_ID;
gorkaion@7647
   444
        Ad_Sequence_Doctype(v_DoctypeReversed_ID, v_Record_ID, 'Y', v_RDocumentNo) ;
gorkaion@7647
   445
        IF (v_RDocumentNo IS NULL) THEN
gorkaion@7647
   446
          Ad_Sequence_Doc('DocumentNo_C_Invoice', v_Client_ID, 'Y', v_RDocumentNo) ;
gorkaion@7647
   447
        END IF;
gorkaion@7647
   448
        v_Message:='@ReversedBy@: ' || v_RDocumentNo;
gorkaion@7647
   449
        --
gorkaion@7647
   450
        DBMS_OUTPUT.PUT_LINE('Reversal Invoice_ID=' || v_RInvoice_ID || ' DocumentNo=' || v_RDocumentNo) ;
gorkaion@7647
   451
        v_ResultStr:='InsertInvoice ID=' || v_RInvoice_ID;
gorkaion@7647
   452
        -- Don't copy C_Payment_ID or C_CashLine_ID
gorkaion@7647
   453
        INSERT INTO C_INVOICE
carlos@0
   454
            (
carlos@0
   455
              C_Invoice_ID, C_Order_ID, AD_Client_ID, AD_Org_ID,
carlos@0
   456
              IsActive, Created, CreatedBy, Updated,
carlos@0
   457
              UpdatedBy, IsSOTrx, DocumentNo, DocStatus,
carlos@0
   458
              DocAction, Processing, Processed, C_DocType_ID,
eduardo@2382
   459
              C_DocTypeTarget_ID, Description, SalesRep_ID,
carlos@1259
   460
              DateInvoiced, DatePrinted, IsPrinted, TaxDate,
carlos@0
   461
              DateAcct, C_PaymentTerm_ID, C_BPartner_ID, C_BPartner_Location_ID,
carlos@0
   462
              AD_User_ID, POReference, DateOrdered, IsDiscountPrinted,
carlos@0
   463
              C_Currency_ID, PaymentRule, C_Charge_ID, ChargeAmt,
carlos@0
   464
              TotalLines, GrandTotal, M_PriceList_ID, C_Campaign_ID,
carlos@0
   465
              C_Project_ID, C_Activity_ID, AD_OrgTrx_ID, User1_ID,
eduardo@7028
   466
              User2_ID, fin_paymentmethod_id
carlos@0
   467
            )
carlos@0
   468
          SELECT v_RInvoice_ID, C_Order_ID, AD_Client_ID, AD_Org_ID,
harikrishnan@7209
   469
            IsActive, now(), v_UpdatedBy, now(),
harikrishnan@7209
   470
            v_UpdatedBy, IsSOTrx, v_RDocumentNo, 'DR',
carlos@0
   471
             'CO', 'N', 'N', v_DoctypeReversed_ID,
eduardo@2382
   472
            v_DoctypeReversed_ID, '(*R*: ' || DocumentNo || ') ' || Description, SalesRep_ID,
rakhee@4301
   473
            now(), NULL, 'N', now(),
rakhee@4301
   474
            now(), C_PaymentTerm_ID, C_BPartner_ID, C_BPartner_Location_ID,
carlos@0
   475
            AD_User_ID, POReference, DateOrdered, IsDiscountPrinted,
carlos@0
   476
            C_Currency_ID, PaymentRule, C_Charge_ID, ChargeAmt * -1,
carlos@0
   477
            TotalLines * -1, GrandTotal * -1, M_PriceList_ID, C_Campaign_ID,
carlos@0
   478
            C_Project_ID, C_Activity_ID, AD_OrgTrx_ID, User1_ID,
eduardo@7028
   479
            User2_ID, fin_paymentmethod_id
carlos@0
   480
          FROM C_INVOICE
carlos@0
   481
          WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   482
        -- Create Reversed invoice relation
gorkaion@7647
   483
        INSERT INTO C_Invoice_Reverse
gorkaion@7647
   484
          (
gorkaion@7647
   485
           C_Invoice_Reverse_ID,AD_Client_ID, AD_Org_ID,
gorkaion@7647
   486
           IsActive, Created, CreatedBy, Updated,
gorkaion@7647
   487
           UpdatedBy, C_Invoice_ID, Reversed_C_Invoice_ID
gorkaion@7647
   488
          )
victor@4940
   489
          SELECT get_uuid(), AD_Client_ID, AD_Org_ID,
harikrishnan@7209
   490
              'Y', now(), v_UpdatedBy, now(),
harikrishnan@7209
   491
              v_UpdatedBy, v_RInvoice_ID, C_Invoice_ID
victor@4940
   492
          FROM C_INVOICE
victor@4940
   493
          WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   494
gorkaion@7647
   495
        --  Delete C_Invoice_Discounts inserted by the trigger
gorkaion@7647
   496
        DELETE FROM C_INVOICE_DISCOUNT WHERE C_Invoice_ID=v_RInvoice_ID;
gorkaion@7647
   497
        --  Insert discounts as in the reversed invoice
gorkaion@7647
   498
        FOR Cur_Discount IN
gorkaion@7647
   499
          (SELECT *
gorkaion@7647
   500
           FROM C_INVOICE_DISCOUNT
gorkaion@7647
   501
           WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
   502
           ORDER BY LINE
gorkaion@7647
   503
          )
gorkaion@7647
   504
        LOOP
gorkaion@7647
   505
          INSERT INTO C_INVOICE_DISCOUNT
gorkaion@7647
   506
            (
gorkaion@7647
   507
              C_INVOICE_DISCOUNT_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE,
gorkaion@7647
   508
              CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@7647
   509
              C_INVOICE_ID, C_DISCOUNT_ID, LINE, CASCADE
carlos@0
   510
            )
gorkaion@7647
   511
            VALUES
gorkaion@7647
   512
            (
gorkaion@7647
   513
              get_uuid(), Cur_Discount.AD_Client_ID, Cur_Discount.AD_Org_ID, 'Y',
gorkaion@7647
   514
              now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7647
   515
              v_RInvoice_ID, Cur_Discount.C_Discount_ID, Cur_Discount.Line, Cur_Discount.CASCADE
gorkaion@7647
   516
            );
gorkaion@7647
   517
        END LOOP;
gorkaion@7647
   518
        -- Create Reversal Invoice Lines
gorkaion@7647
   519
        FOR Cur_InvoiceLine IN
gorkaion@7647
   520
          (SELECT *
gorkaion@7647
   521
           FROM C_INVOICELINE
gorkaion@7647
   522
           WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
   523
             AND C_INVOICE_DISCOUNT_ID IS NULL
gorkaion@7647
   524
           ORDER BY Line
gorkaion@7647
   525
          )
gorkaion@7647
   526
        LOOP
gorkaion@7647
   527
          v_NextNo := get_uuid();
gorkaion@7647
   528
          INSERT INTO C_INVOICELINE
gorkaion@7647
   529
            (
gorkaion@7647
   530
              C_InvoiceLine_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@7647
   531
              Created, CreatedBy, Updated, UpdatedBy,
gorkaion@7647
   532
              C_Invoice_ID, C_OrderLine_ID, M_InOutLine_ID, Line,
gorkaion@7647
   533
              Description, M_Product_ID, QtyInvoiced, PriceList,
gorkaion@7647
   534
              PriceActual, LineNetAmt, C_Charge_ID, ChargeAmt,
gorkaion@7647
   535
              C_UOM_ID, C_Tax_ID, PriceStd)
gorkaion@7647
   536
            VALUES
gorkaion@7647
   537
            (
gorkaion@7647
   538
              v_NextNo, Cur_InvoiceLine.AD_Client_ID, Cur_InvoiceLine.AD_Org_ID, 'Y',
gorkaion@7647
   539
              now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7647
   540
              v_RInvoice_ID, Cur_InvoiceLine.C_OrderLine_ID, Cur_InvoiceLine.M_InoutLine_ID, Cur_InvoiceLine.Line,
gorkaion@7647
   541
               '*R*: ' || Cur_InvoiceLine.Description, Cur_InvoiceLine.M_Product_ID, Cur_InvoiceLine.QtyInvoiced * -1, Cur_InvoiceLine.PriceList,
gorkaion@7647
   542
              Cur_InvoiceLine.PriceActual, Cur_InvoiceLine.LineNetAmt * -1, Cur_InvoiceLine.C_Charge_ID, Cur_InvoiceLine.ChargeAmt * -1,
gorkaion@7647
   543
              Cur_InvoiceLine.C_UOM_ID, Cur_InvoiceLine.C_Tax_ID, Cur_InvoiceLine.PriceStd
gorkaion@7647
   544
            );
gorkaion@7647
   545
          INSERT INTO M_MATCHINV
gorkaion@7647
   546
            (M_MATCHINV_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@7647
   547
            M_INOUTLINE_ID, C_INVOICELINE_ID, M_PRODUCT_ID, DATETRX, QTY, PROCESSING, PROCESSED, POSTED)
david@7191
   548
            SELECT
gorkaion@7647
   549
              get_uuid(), AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, now(), v_UpdatedBy, now(), v_UpdatedBy,
david@7195
   550
              M_INOUTLINE_ID, v_NextNo, M_PRODUCT_ID, DATETRX, -QTY, 'N', 'Y', 'N'
david@7191
   551
            FROM M_MATCHINV
david@7197
   552
            WHERE C_INVOICELINE_ID = Cur_InvoiceLine.C_InvoiceLine_ID;
gorkaion@7647
   553
          /* OrderLine.qtyInvoiced is updated in c_invoicePost
gorkaion@7647
   554
          UPDATE C_OrderLine
gorkaion@7647
   555
          SET QtyInvoiced = QtyInvoiced - Cur_InvoiceLine.QtyInvoiced,
gorkaion@7647
   556
              Updated = now(),
gorkaion@7647
   557
              UpdatedBy=v_UpdatedBy
gorkaion@7647
   558
          WHERE C_OrderLine_ID=Cur_InvoiceLine.C_OrderLine_ID; */
gorkaion@7647
   559
        END LOOP; -- Create Reversal Invoice Lines
gorkaion@7647
   560
        -- Close Invoice
gorkaion@7647
   561
        UPDATE C_INVOICE
gorkaion@7647
   562
        SET DocStatus='VO', -- it IS reversed
gorkaion@239
   563
            Description=COALESCE(TO_CHAR(Description), '') || ' (*R* -> ' || v_RDocumentNo || ')',
carlos@0
   564
            DocAction='--',
carlos@0
   565
            Processed='Y',
antonio@735
   566
            Updated=now()
gorkaion@7647
   567
        WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   568
        -- Post Reversal
gorkaion@7647
   569
        C_INVOICE_POST(NULL, v_RInvoice_ID) ;
gorkaion@7647
   570
        -- Reversal Transaction is closed
gorkaion@7647
   571
        UPDATE C_INVOICE
gorkaion@7647
   572
        SET DocStatus='VO', -- the reversal transaction
carlos@0
   573
            DocAction='--',
carlos@0
   574
            Processed='Y'
gorkaion@7647
   575
        WHERE C_Invoice_ID=v_RInvoice_ID;
gorkaion@7647
   576
        -- If Payments from both invoices are pending, create a new settlement and cancel them
gorkaion@7647
   577
        SELECT COUNT(*) INTO v_count
gorkaion@7647
   578
        FROM C_DEBT_PAYMENT dp
gorkaion@7647
   579
        WHERE C_Debt_Payment_Status(dp.C_Settlement_Cancel_ID, dp.Cancel_Processed, dp.Generate_Processed, dp.IsPaid, dp.IsValid, dp.C_CashLine_ID, dp.C_BankStatementLine_ID)<>'P'
gorkaion@7647
   580
          AND(dp.C_Invoice_ID=v_Record_ID
gorkaion@7647
   581
          OR dp.C_Invoice_ID=v_RInvoice_ID) ;
gorkaion@7647
   582
        -- To cancel, the sum of amounts should be 0
gorkaion@7647
   583
        IF (v_count=0) THEN
gorkaion@7647
   584
          SELECT SUM(AMOUNT) INTO v_count
carlos@0
   585
          FROM C_DEBT_PAYMENT dp
gorkaion@7647
   586
          WHERE dp.C_Invoice_ID=v_Record_ID
gorkaion@7647
   587
            OR dp.C_Invoice_ID=v_RInvoice_ID;
gorkaion@7647
   588
          IF (v_count=0) THEN
gorkaion@7647
   589
            v_SettlementDocType_ID:=Ad_Get_Doctype(v_Client_ID, v_Org_ID, TO_CHAR('STT')) ;
gorkaion@7647
   590
            v_settlementID := get_uuid();
gorkaion@7647
   591
            Ad_Sequence_Doctype(v_SettlementDocType_ID, v_Record_ID, 'Y', v_SDocumentNo) ;
gorkaion@7647
   592
            IF (v_SDocumentNo IS NULL) THEN
gorkaion@7647
   593
              Ad_Sequence_Doc('DocumentNo_C_Settlement', v_Client_ID, 'Y', v_SDocumentNo) ;
gorkaion@7647
   594
            END IF;
gorkaion@7647
   595
            INSERT
gorkaion@7647
   596
            INTO C_SETTLEMENT
gorkaion@7647
   597
              (
gorkaion@7647
   598
                C_SETTLEMENT_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE,
gorkaion@7647
   599
                CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@7647
   600
                DOCUMENTNO, DATETRX, DATEACCT, SETTLEMENTTYPE,
gorkaion@7647
   601
                C_DOCTYPE_ID, PROCESSING, PROCESSED, POSTED,
gorkaion@7647
   602
                C_CURRENCY_ID, C_PROJECT_ID, C_CAMPAIGN_ID, C_ACTIVITY_ID,
gorkaion@7647
   603
                USER1_ID, USER2_ID, CREATEFROM, ISGENERATED
gorkaion@7647
   604
              )
carlos@0
   605
              SELECT v_settlementID, AD_Client_ID, AD_Org_ID, 'Y',
harikrishnan@7209
   606
                now(), v_UpdatedBy, now(), v_UpdatedBy,
antonio@735
   607
                '*RE*'||v_SDocumentNo, TRUNC(now()), TRUNC(now()), 'C',
carlos@0
   608
                v_SettlementDocType_ID, 'N', 'N', 'N',
carlos@0
   609
                C_Currency_ID, C_PROJECT_ID, C_CAMPAIGN_ID, C_ACTIVITY_ID,
carlos@0
   610
                USER1_ID, USER2_ID, 'N', 'Y'
carlos@0
   611
              FROM C_INVOICE
carlos@0
   612
              WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   613
            UPDATE C_DEBT_PAYMENT
gorkaion@7647
   614
            SET C_Settlement_Cancel_id=v_settlementID,
antonio@735
   615
                UPDATED=now(),
carlos@0
   616
                UPDATEDBY=v_UpdatedBy
gorkaion@7647
   617
            WHERE C_DEBT_PAYMENT.C_Invoice_ID=v_Record_ID
gorkaion@7647
   618
              OR C_DEBT_PAYMENT.C_Invoice_ID=v_RInvoice_ID;
gorkaion@7647
   619
            C_SETTLEMENT_POST(NULL, v_settlementID) ;
gorkaion@7647
   620
          END IF;
gorkaion@7647
   621
        END IF;
gorkaion@7647
   622
        END_PROCESSING:=TRUE;
gorkaion@7647
   623
      END IF;
gorkaion@7647
   624
      EXCEPTION WHEN OTHERS THEN RAISE NO_DATA_FOUND;
gorkaion@7647
   625
    END; -- FOR COMMIT
gorkaion@7647
   626
  END IF;--FINISH_PROCESS
gorkaion@7647
   627
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
   628
    /**************************************************************************
gorkaion@7647
   629
     * Credit Multiplier
gorkaion@7647
   630
     *************************************************************************/
gorkaion@7647
   631
    DECLARE
gorkaion@7647
   632
      v_DocBaseType C_DOCTYPE.DocBaseType%TYPE;
gorkaion@7647
   633
    BEGIN
gorkaion@7647
   634
      -- Is it a Credit Memo?
gorkaion@7647
   635
      SELECT DocBaseType INTO v_DocBaseType
gorkaion@7647
   636
      FROM C_DOCTYPE
gorkaion@7647
   637
      WHERE C_DocType_ID=v_DocType_ID;
gorkaion@7647
   638
      IF (v_DocBaseType IN('ARC', 'API')) THEN
gorkaion@7647
   639
        v_Multiplier:=-1;
gorkaion@7647
   640
      END IF;
gorkaion@7647
   641
    END;
gorkaion@7647
   642
  END IF;--FINISH_PROCESS
gorkaion@7647
   643
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
   644
    /************************************************************************
gorkaion@7647
   645
     * Actions allowed: Reactivate
gorkaion@7647
   646
     * Modified by Jon Alegria
gorkaion@7647
   647
     */
gorkaion@7647
   648
    IF (v_DocAction='RE') THEN
gorkaion@7647
   649
      IF (v_DocStatus<>'CO') THEN
gorkaion@7647
   650
        RAISE_APPLICATION_ERROR(-20000, '@NotCompletedInvoice@');
gorkaion@7647
   651
      END IF;
gorkaion@7647
   652
      IF (v_Posted='Y') THEN
gorkaion@7647
   653
        RAISE_APPLICATION_ERROR(-20000, '@InvoiceDocumentPosted@');
gorkaion@7647
   654
      END IF;
gorkaion@7647
   655
      SELECT COUNT(*), MAX(C_DEBT_PAYMENT_ID)
gorkaion@7647
   656
        INTO v_Count, v_Debtpayment_ID
gorkaion@7647
   657
      FROM C_DEBT_PAYMENT
gorkaion@7647
   658
      WHERE C_DEBT_PAYMENT.C_Invoice_ID=v_Record_ID
gorkaion@7647
   659
        AND C_Debt_Payment_Status(C_Settlement_Cancel_ID, Cancel_Processed, C_DEBT_PAYMENT.Generate_Processed, IsPaid, IsValid, C_Cashline_ID, C_BankstatementLine_ID)<>'P'
gorkaion@7647
   660
        AND C_ORDER_ID IS NULL;
gorkaion@7647
   661
      IF (v_Count<>0) THEN
gorkaion@7647
   662
        --Added by P.Sarobe. New messages
gorkaion@7647
   663
        SELECT c_Bankstatementline_Id, c_cashline_id, c_settlement_cancel_id, ispaid, cancel_processed
gorkaion@7647
   664
          INTO v_Bankstatementline_ID, v_CashLine_ID, v_Settlement_Cancel_ID, v_ispaid, v_Cancel_Processed
gorkaion@7647
   665
        FROM C_DEBT_PAYMENT
gorkaion@7647
   666
        WHERE C_Debt_Payment_ID = v_Debtpayment_ID;
gorkaion@7647
   667
        IF (v_Bankstatementline_ID IS NOT NULL) THEN
gorkaion@7647
   668
          SELECT C_BANKSTATEMENT.NAME, C_BANKSTATEMENT.STATEMENTDATE
gorkaion@7647
   669
            INTO v_nameBankstatement, v_dateBankstatement
gorkaion@7647
   670
          FROM C_BANKSTATEMENT, C_BANKSTATEMENTLINE
gorkaion@7647
   671
          WHERE C_BANKSTATEMENT.C_BANKSTATEMENT_ID = C_BANKSTATEMENTLINE.C_BANKSTATEMENT_ID
gorkaion@7647
   672
            AND C_BANKSTATEMENTLINE.C_BANKSTATEMENTLINE_ID = v_Bankstatementline_ID;
gorkaion@7647
   673
          RAISE_APPLICATION_ERROR(-20000, '@ManagedDebtPaymentInvoiceBank@'||v_nameBankstatement||' '||'@Bydate@'||v_dateBankstatement) ;
gorkaion@7647
   674
        END IF;
gorkaion@7647
   675
        IF (v_CashLine_ID IS NOT NULL) THEN
gorkaion@7647
   676
          SELECT C_CASH.NAME, C_CASH.STATEMENTDATE
gorkaion@7647
   677
            INTO v_nameCash, v_dateCash
gorkaion@7647
   678
          FROM C_CASH, C_CASHLINE
gorkaion@7647
   679
          WHERE C_CASH.C_CASH_ID = C_CASHLINE.C_CASH_ID
gorkaion@7647
   680
            AND C_CASHLINE.C_CASHLINE_ID = v_CashLine_ID;
gorkaion@7647
   681
          RAISE_APPLICATION_ERROR(-20000, '@ManagedDebtPaymentInvoiceCash@'||v_nameCash||' '||'@Bydate@'||v_dateCash) ;
gorkaion@7647
   682
        END IF;
gorkaion@7647
   683
        IF (v_Cancel_Processed='Y' AND v_ispaid='N') THEN
gorkaion@7647
   684
          SELECT documentno, datetrx
gorkaion@7647
   685
            INTO v_documentno_Settlement, v_dateSettlement
gorkaion@7647
   686
          FROM C_SETTLEMENT
gorkaion@7647
   687
          WHERE C_SETTLEMENT_ID = v_Settlement_Cancel_ID;
gorkaion@7647
   688
          RAISE_APPLICATION_ERROR(-20000, '@ManagedDebtPaymentOrderCancel@'||v_documentno_Settlement||' '||'@Bydate@'||v_dateSettlement) ;
gorkaion@7647
   689
        END IF;
gorkaion@7647
   690
      END IF;
gorkaion@7647
   691
      SELECT COUNT(*) INTO v_Count
gorkaion@7647
   692
      FROM C_DP_MANAGEMENTLINE ml,
gorkaion@7647
   693
           C_DP_MANAGEMENT m,
gorkaion@7647
   694
           C_DEBT_PAYMENT dp
gorkaion@7647
   695
      WHERE ml.C_DP_Management_ID=m.C_DP_Management_ID
gorkaion@7647
   696
        AND ml.C_Debt_Payment_ID=dp.C_Debt_Payment_ID
gorkaion@7647
   697
        AND dp.C_Invoice_ID=v_Record_ID
gorkaion@7647
   698
        AND m.processed='Y';
gorkaion@7647
   699
      IF (v_Count!=0) THEN
gorkaion@7647
   700
        RAISE_APPLICATION_ERROR(-20000, '@DPInvoiceManaged@');
gorkaion@7647
   701
      END IF;
gorkaion@7647
   702
      -- Pending undo not Stocked BOM's
gorkaion@7647
   703
      -- Undo BP Statictis
gorkaion@7647
   704
      --Undo first sale
gorkaion@7647
   705
      SELECT MIN(DateAcct) INTO v_FirstSales
gorkaion@7647
   706
      FROM C_INVOICE
gorkaion@7647
   707
      WHERE C_Invoice_ID<>v_Record_ID
gorkaion@7647
   708
        AND C_BPartner_ID=v_BPartner_ID;
gorkaion@7647
   709
      UPDATE C_BPARTNER  SET FirstSale=v_FirstSales  WHERE C_BPartner_ID=v_BPartner_ID;
gorkaion@7647
   710
      -- Undo Last contact
gorkaion@7647
   711
      FOR Cur_LastContact IN
gorkaion@7647
   712
        (SELECT Updated, DocumentNo, Ad_User_ID
gorkaion@7647
   713
         FROM C_INVOICE
gorkaion@7647
   714
         WHERE C_Invoice_ID<>v_Record_ID
gorkaion@7647
   715
           AND Ad_User_ID=v_BPartner_User_ID
gorkaion@7647
   716
         ORDER BY Updated DESC
gorkaion@7647
   717
        )
gorkaion@7647
   718
      LOOP
gorkaion@7647
   719
        UPDATE AD_USER
gorkaion@7647
   720
        SET LastContact=Cur_LastContact.Updated,
gorkaion@7647
   721
            LastResult=Cur_LastContact.DocumentNo
gorkaion@7647
   722
        WHERE AD_User_ID=Cur_LastContact.Ad_User_ID;
gorkaion@7647
   723
        EXIT;
gorkaion@7647
   724
      END LOOP;
gorkaion@7647
   725
      IF (v_IsSOTrx='Y') THEN
gorkaion@7647
   726
        -- Undo revenue and credit limit
gorkaion@7647
   727
        UPDATE C_BPARTNER
gorkaion@7647
   728
        SET ActualLifeTimeValue=ActualLifeTimeValue -(v_Multiplier *  C_Base_Convert(v_GrandTotal, v_Currency_ID, v_Client_ID, v_DateAcct, v_Org_ID))
gorkaion@7647
   729
        WHERE C_BPartner_ID=v_BPartner_ID;
gorkaion@7647
   730
        FOR Cur_ReactivateInvoiceLine IN
gorkaion@7647
   731
          (SELECT C_InvoiceLine_ID, C_Orderline_ID, M_InoutLine_ID, QtyInvoiced
gorkaion@7647
   732
           FROM C_INVOICELINE
gorkaion@7647
   733
           WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
   734
          )
gorkaion@7647
   735
        LOOP
gorkaion@7647
   736
          IF (Cur_ReactivateInvoiceLine.C_OrderLine_ID IS NOT NULL) THEN
gorkaion@7647
   737
            SELECT MAX(C_INVOICE.DateInvoiced) INTO v_REDateInvoiced
gorkaion@7647
   738
            FROM C_INVOICE, C_INVOICELINE
gorkaion@7647
   739
            WHERE C_INVOICE.C_Invoice_ID=C_INVOICELINE.C_INVOICE_ID
gorkaion@7647
   740
              AND C_INVOICELINE.C_ORDERLINE_ID=Cur_ReactivateInvoiceLine.C_ORDERLINE_ID
gorkaion@7647
   741
              AND C_INVOICELINE.C_InvoiceLine_ID<>Cur_ReactivateInvoiceLine.C_InvoiceLine_ID;
gorkaion@7647
   742
            UPDATE C_ORDERLINE
gorkaion@7647
   743
            SET QtyInvoiced=QtyInvoiced - Cur_ReactivateInvoiceLine.QtyInvoiced,
gorkaion@7647
   744
                DateInvoiced=v_REDateInvoiced,
gorkaion@7647
   745
                Updated=now(),
gorkaion@7647
   746
                UpdatedBy=v_UpdatedBy
gorkaion@7647
   747
            WHERE C_ORDERLINE.C_OrderLine_ID=Cur_ReactivateInvoiceLine.C_OrderLine_ID;
gorkaion@7647
   748
          END IF;
gorkaion@7647
   749
          IF (Cur_ReactivateInvoiceLine.M_InOutLine_ID IS NOT NULL) THEN
gorkaion@7647
   750
            SELECT m.DOCSTATUS INTO v_REInOutStatus
gorkaion@7647
   751
            FROM M_INOUT m, M_INOUTLINE ml
gorkaion@7647
   752
            WHERE M.M_InOut_ID=ml.M_InOut_ID
gorkaion@7647
   753
              AND ml.M_InOutLine_ID=Cur_ReactivateInvoiceLine.M_InOutLine_ID;
gorkaion@7647
   754
            IF (v_REInOutStatus<>'RE') THEN
gorkaion@7647
   755
              SELECT COALESCE(SUM(C_INVOICELINE.QTYINVOICED), 0) INTO v_REtotalQtyInvoiced
gorkaion@7647
   756
              FROM C_INVOICELINE, C_INVOICE
gorkaion@7647
   757
              WHERE C_INVOICE.C_Invoice_ID=C_INVOICELINE.C_Invoice_ID
gorkaion@7647
   758
                AND C_INVOICE.Processed='Y'
gorkaion@7647
   759
                AND C_INVOICELINE.M_InOutLine_ID=Cur_ReactivateInvoiceLine.M_InOutLine_ID;
gorkaion@7647
   760
              v_REtotalQtyInvoiced:=v_REtotalQtyInvoiced - Cur_ReactivateInvoiceLine.QtyInvoiced;
gorkaion@7647
   761
              SELECT MovementQty INTO v_REdeliveredQty
gorkaion@7647
   762
              FROM M_INOUTLINE
gorkaion@7647
   763
              WHERE M_InOutLine_ID=Cur_ReactivateInvoiceLine.M_InOutLine_ID;
gorkaion@7647
   764
              UPDATE M_INOUTLINE
gorkaion@7647
   765
              SET IsInvoiced=(
gorkaion@7647
   766
                     CASE v_REtotalQtyInvoiced
gorkaion@7647
   767
                        WHEN 0 THEN 'N'
gorkaion@7647
   768
                        ELSE 'Y'
gorkaion@7647
   769
                     END)
gorkaion@7647
   770
              WHERE M_InOutLine_ID=Cur_ReactivateInvoiceLine.M_InOutLine_ID;
carlos@0
   771
            END IF;
carlos@0
   772
          END IF;
gorkaion@7647
   773
        END LOOP;
gorkaion@7647
   774
      ELSE
gorkaion@7647
   775
        -- When re-activating an invoice, match invoice lines are removed (if not posted)
gorkaion@7647
   776
        SELECT COUNT(1) INTO v_count
gorkaion@7647
   777
        FROM FACT_ACCT
gorkaion@7647
   778
        WHERE AD_TABLE_ID = (SELECT AD_TABLE_ID 
gorkaion@7647
   779
                             FROM AD_TABLE
gorkaion@7647
   780
                             WHERE UPPER(TABLENAME) LIKE 'M_MATCHPO')
gorkaion@7647
   781
                                AND RECORD_ID IN (SELECT M_MATCHPO_ID
gorkaion@7647
   782
                                                  FROM M_MATCHPO MP, C_INVOICE I, C_INVOICELINE IL
gorkaion@7647
   783
                                                  WHERE I.C_INVOICE_ID=IL.C_INVOICE_ID
gorkaion@7647
   784
                                                    AND MP.C_INVOICELINE_ID=IL.C_INVOICELINE_ID
gorkaion@7647
   785
                                                    AND I.C_INVOICE_ID=v_Record_ID);
gorkaion@7647
   786
        IF (v_count>0) THEN
gorkaion@7647
   787
          RAISE_APPLICATION_ERROR(-20000, '@PostedMatchPO@');
carlos@0
   788
        END IF;
gorkaion@7647
   789
        DELETE FROM M_MATCHPO
gorkaion@7647
   790
        WHERE C_InvoiceLine_ID IN (SELECT C_InvoiceLine_ID FROM C_INVOICELINE WHERE C_Invoice_ID=v_Record_ID);
gorkaion@7647
   791
      END IF;
gorkaion@7647
   792
      UPDATE C_INVOICE
gorkaion@7647
   793
      SET Processed='N',
gorkaion@7647
   794
          DocStatus='DR',
gorkaion@7647
   795
          DocAction='CO',Updated=now(),
gorkaion@7647
   796
          UpdatedBy=v_UpdatedBy
gorkaion@7647
   797
      WHERE C_Invoice_Id=v_Record_ID;
gorkaion@7647
   798
      --Delete automatically created records ...
gorkaion@7647
   799
      DELETE FROM C_CASHLINE
gorkaion@7647
   800
      WHERE ISGENERATED='Y'
gorkaion@7647
   801
        AND C_DEBT_PAYMENT_ID IN
gorkaion@7647
   802
          (SELECT C_DEBT_PAYMENT_ID
gorkaion@7647
   803
           FROM C_DEBT_PAYMENT
gorkaion@7647
   804
           WHERE C_INVOICE_ID=v_Record_ID)
gorkaion@7647
   805
             AND C_CASH_ID IN (SELECT C_CASH_ID FROM C_CASH WHERE PROCESSED='N');
gorkaion@7647
   806
      -- Updates the debt-payments of the cash, to make them not to point to the invoice
gorkaion@7647
   807
      UPDATE C_DEBT_PAYMENT
gorkaion@7647
   808
      SET C_INVOICE_ID=NULL
gorkaion@7647
   809
      WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
   810
        AND C_Order_ID IS NOT NULL;
gorkaion@7647
   811
      DELETE FROM C_DEBT_PAYMENT
gorkaion@7647
   812
      WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
   813
        AND COALESCE(IsAutomaticGenerated, 'Y')='Y'
gorkaion@7647
   814
        AND C_ORDER_ID IS NULL;
gorkaion@7647
   815
      UPDATE C_DEBT_PAYMENT
gorkaion@7647
   816
      SET IsValid='N',Updated=now(),
gorkaion@7647
   817
          UpdatedBy=v_UpdatedBy
gorkaion@7647
   818
      WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
   819
        AND COALESCE(IsAutomaticGenerated, 'Y')='N'
gorkaion@7647
   820
        AND C_ORDER_ID IS NULL;
gorkaion@7647
   821
      IF (v_IsSOTrx='Y') THEN
gorkaion@7647
   822
        C_BP_SOCREDITUSED_REFRESH(v_BPartner_ID) ;
gorkaion@7647
   823
      END IF;
gorkaion@7647
   824
      DELETE FROM C_INVOICELINE
gorkaion@7647
   825
      WHERE C_INVOICE_DISCOUNT_ID IS NOT NULL
gorkaion@7647
   826
        AND C_INVOICE_ID=v_Record_ID;
gorkaion@7647
   827
      END_PROCESSING:=TRUE;
gorkaion@7647
   828
    END IF;
gorkaion@7647
   829
  END IF;--END_PROCESSING
gorkaion@7647
   830
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
   831
    /**************************************************************************
gorkaion@7647
   832
     * Actions allowed: COmplete, APprove
gorkaion@7647
   833
     */
gorkaion@7647
   834
    IF (v_DocAction='AP' OR v_DocAction='CO') THEN
gorkaion@7647
   835
      -- Check the header belongs to a organization where transactions are posible and ready to use
gorkaion@7647
   836
      SELECT AD_Org.IsReady, Ad_OrgType.IsTransactionsAllowed
gorkaion@7647
   837
        INTO v_is_ready, v_is_tr_allow
gorkaion@7647
   838
      FROM C_INVOICE, AD_Org, AD_OrgType
gorkaion@7647
   839
      WHERE AD_Org.AD_Org_ID=C_INVOICE.AD_Org_ID
gorkaion@7647
   840
        AND AD_Org.AD_OrgType_ID=AD_OrgType.AD_OrgType_ID
gorkaion@7647
   841
        AND C_INVOICE.C_INVOICE_ID=v_Record_ID;
gorkaion@7647
   842
      IF (v_is_ready='N') THEN
gorkaion@7647
   843
        RAISE_APPLICATION_ERROR(-20000, '@OrgHeaderNotReady@');
gorkaion@7647
   844
      END IF;
gorkaion@7647
   845
      IF (v_is_tr_allow='N') THEN
gorkaion@7647
   846
        RAISE_APPLICATION_ERROR(-20000, '@OrgHeaderNotTransAllowed@');
gorkaion@7647
   847
      END IF;
gorkaion@7647
   848
gorkaion@7647
   849
      SELECT AD_ORG_CHK_DOCUMENTS('C_INVOICE', 'C_INVOICELINE', v_Record_ID, 'C_INVOICE_ID', 'C_INVOICE_ID') INTO v_is_included FROM dual;
gorkaion@7647
   850
      IF (v_is_included=-1) THEN
gorkaion@7647
   851
        RAISE_APPLICATION_ERROR(-20000, '@LinesAndHeaderDifferentLEorBU@');
gorkaion@7647
   852
      END IF;
gorkaion@7647
   853
gorkaion@7647
   854
      -- Check the period control is opened (only if it is legal entity with accounting)
gorkaion@7647
   855
      -- Gets the BU or LE of the document
gorkaion@7647
   856
      SELECT AD_GET_DOC_LE_BU('C_INVOICE', v_Record_ID, 'C_INVOICE_ID', 'LE') INTO v_org_bule_id FROM DUAL;
gorkaion@7647
   857
      SELECT AD_OrgType.IsAcctLegalEntity INTO v_isacctle
gorkaion@7647
   858
      FROM AD_OrgType, AD_Org
gorkaion@7647
   859
      WHERE AD_Org.AD_OrgType_ID = AD_OrgType.AD_OrgType_ID
gorkaion@7647
   860
        AND AD_Org.AD_Org_ID=v_org_bule_id;
gorkaion@7647
   861
gorkaion@7647
   862
      IF (v_isacctle='Y') THEN
gorkaion@7647
   863
        SELECT C_CHK_OPEN_PERIOD(v_Org_ID, v_DateAcct, NULL, v_DocTypeTarget_ID) INTO v_available_period FROM DUAL;
gorkaion@7647
   864
        IF (v_available_period<>1) THEN
gorkaion@7647
   865
          RAISE_APPLICATION_ERROR(-20000, '@PeriodNotAvailable@');
gorkaion@7647
   866
        END IF;
gorkaion@7647
   867
      END IF;
gorkaion@7647
   868
gorkaion@7647
   869
      SELECT COUNT(*) INTO v_count
gorkaion@7647
   870
      FROM C_INVOICE c, C_BPARTNER bp
gorkaion@7647
   871
      WHERE c.C_BPARTNER_ID=bp.C_BPARTNER_ID
gorkaion@7647
   872
        AND Ad_Isorgincluded(c.AD_ORG_ID, bp.AD_ORG_ID, bp.AD_CLIENT_ID)=-1
gorkaion@7647
   873
        AND c.C_Invoice_ID=v_Record_ID;
gorkaion@7647
   874
      IF (v_count>0) THEN
gorkaion@7647
   875
        RAISE_APPLICATION_ERROR(-20000, '@NotCorrectOrgBpartnerInvoice@') ;
gorkaion@7647
   876
      END IF;
gorkaion@7647
   877
      WHILE(v_DocType_ID<>v_DocTypeTarget_ID)
gorkaion@7647
   878
      LOOP
carlos@0
   879
        BEGIN
gorkaion@7647
   880
          v_ResultStr:='UpdateDocType';
gorkaion@7647
   881
          UPDATE C_INVOICE
gorkaion@7647
   882
          SET C_DocType_ID=C_DocTypeTarget_ID,
gorkaion@7647
   883
              Updated=now(),
gorkaion@7647
   884
              UpdatedBy=v_UpdatedBy
gorkaion@7647
   885
          WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
   886
          v_DocType_ID:=v_DocTypeTarget_ID;
gorkaion@7647
   887
        EXCEPTION
gorkaion@7647
   888
          WHEN OTHERS THEN
gorkaion@7647
   889
            v_ResultStr:='UpdateDocumentNo';
gorkaion@7647
   890
            UPDATE C_INVOICE
gorkaion@7647
   891
              SET DocumentNo=DocumentNo || '.'
gorkaion@7647
   892
            WHERE C_Invoice_ID=v_Record_ID;
carlos@0
   893
        END;
gorkaion@7647
   894
      END LOOP;
gorkaion@7647
   895
    ELSE
gorkaion@7647
   896
      v_Message:='@ActionNotAllowedHere@ (I-' || v_DocAction || ')';
carlos@0
   897
      RAISE_APPLICATION_ERROR(-20000, v_Message) ;
gorkaion@7647
   898
      END_PROCESSING:=TRUE;
gorkaion@7647
   899
    END IF;
gorkaion@7647
   900
  END IF;--FINISH_PROCESS
gorkaion@7647
   901
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
   902
    /**************************************************************************
gorkaion@7647
   903
     * Resolve not-stocked BOMs
gorkaion@7647
   904
     *************************************************************************/
gorkaion@7647
   905
    DECLARE
gorkaion@7647
   906
      -- Invoice Lines with non-stocked BOMs
gorkaion@7647
   907
      CUR_BOM_Line RECORD;
gorkaion@7647
   908
      CUR_BOM RECORD;
gorkaion@7647
   909
      CUR_PriceList_Version RECORD;
gorkaion@7647
   910
      --
gorkaion@7647
   911
      CountNo NUMBER;
gorkaion@7647
   912
      v_PriceList_Version_ID VARCHAR2(32);
gorkaion@7647
   913
      v_Line NUMBER;
gorkaion@7647
   914
      v_ChargeAmt NUMBER;
gorkaion@7647
   915
      -- v_Offer_ID       varchar2(32);
gorkaion@7647
   916
      v_DateInvoiced DATE;
gorkaion@7647
   917
      v_BPartner_ID VARCHAR2(32);
gorkaion@7647
   918
      v_PriceList_ID VARCHAR2(32);
gorkaion@7647
   919
      --
gorkaion@7647
   920
    BEGIN
gorkaion@7647
   921
      v_ResultStr:='ResolveBOM';
gorkaion@7647
   922
      LOOP
gorkaion@7647
   923
        -- How many BOMs do we have:1
gorkaion@7647
   924
        SELECT COUNT(*) INTO CountNo
gorkaion@7647
   925
        FROM C_INVOICELINE l
gorkaion@7647
   926
        WHERE l.C_Invoice_ID=v_Record_ID
gorkaion@7647
   927
          AND EXISTS
gorkaion@7647
   928
              (SELECT *
gorkaion@7647
   929
               FROM M_PRODUCT p
gorkaion@7647
   930
               WHERE l.M_Product_ID=p.M_Product_ID
gorkaion@7647
   931
                 AND p.IsBOM='Y'
gorkaion@7647
   932
                 AND p.IsStocked='N'
gorkaion@7647
   933
                 AND p.productType='I'
gorkaion@7647
   934
              );
gorkaion@7647
   935
        -- Nothing to do:2
gorkaion@7647
   936
        EXIT WHEN CountNo=0;
gorkaion@7647
   937
        DBMS_OUTPUT.PUT_LINE('  BOMs to resolve=' || CountNo) ;
gorkaion@7647
   938
        -- Get Price List Version
gorkaion@7647
   939
        FOR CUR_PriceList_Version IN
gorkaion@7647
   940
          (SELECT COALESCE(v.M_PriceList_Version_ID, '0') AS PriceList_Version_ID, o.M_PriceList_ID AS M_PriceLIst_ID
gorkaion@7647
   941
           FROM M_PRICELIST_VERSION v, C_INVOICE o
gorkaion@7647
   942
           WHERE v.M_PriceList_ID=o.M_PriceList_ID
gorkaion@7647
   943
             AND v.ValidFrom<=o.DateOrdered
gorkaion@7647
   944
             AND v.IsActive='Y'
gorkaion@7647
   945
             AND o.C_Invoice_ID=v_Record_ID
gorkaion@7647
   946
           ORDER BY v.ValidFrom DESC
gorkaion@7647
   947
          )
gorkaion@7647
   948
        LOOP
gorkaion@7647
   949
          v_PriceList_Version_ID:=CUR_PriceList_Version.PriceList_Version_ID;
gorkaion@7647
   950
          v_PriceList_ID := CUR_PriceList_Version.M_PriceList_ID;
gorkaion@7647
   951
          EXIT;
gorkaion@7647
   952
        END LOOP;
gorkaion@7647
   953
        --Reference Date for price DateOrdered
gorkaion@7647
   954
        SELECT C_BPARTNER_ID, DATEORDERED
gorkaion@7647
   955
          INTO v_BPartner_ID, v_DateInvoiced
gorkaion@7647
   956
        FROM C_INVOICE
gorkaion@7647
   957
        WHERE C_INVOICE_ID=v_Record_ID;
gorkaion@7647
   958
        -- Replace Lines
gorkaion@7647
   959
        FOR CUR_BOM_Line IN
gorkaion@7647
   960
          (SELECT *
gorkaion@7647
   961
           FROM C_INVOICELINE l
gorkaion@7647
   962
           WHERE l.C_Invoice_ID=v_Record_ID
gorkaion@7647
   963
             AND IsActive='Y'
gorkaion@7647
   964
             AND EXISTS
gorkaion@7647
   965
                (SELECT *
gorkaion@7647
   966
                 FROM M_PRODUCT p
gorkaion@7647
   967
                 WHERE l.M_Product_ID=p.M_Product_ID
gorkaion@7647
   968
                   AND p.IsBOM='Y'
gorkaion@7647
   969
                   AND p.IsStocked='N'
gorkaion@7647
   970
                   AND p.productType='I'
gorkaion@7647
   971
                 )
gorkaion@7647
   972
           ORDER BY l.Line  FOR UPDATE
gorkaion@7647
   973
          )
gorkaion@7647
   974
        LOOP
gorkaion@7647
   975
          v_Line:=CUR_BOM_Line.Line;
gorkaion@7647
   976
          -- One Time variables
gorkaion@7647
   977
          v_ChargeAmt:=CUR_BOM_Line.ChargeAmt;
gorkaion@7647
   978
          -- Create New Lines
gorkaion@7647
   979
          FOR CUR_BOM IN
gorkaion@7647
   980
            (SELECT b.M_ProductBOM_ID, p.C_UOM_ID, b.BOMQty, b.Description
gorkaion@7647
   981
             FROM M_PRODUCT_BOM b, M_PRODUCT p
gorkaion@7647
   982
             WHERE b.M_Product_ID=CUR_BOM_Line.M_Product_ID
gorkaion@7647
   983
               AND b.M_ProductBOM_ID=p.M_Product_ID
gorkaion@7647
   984
             ORDER BY Line
gorkaion@7647
   985
            )
carlos@0
   986
          LOOP
gorkaion@7647
   987
            v_Line:=v_Line + 10;
gorkaion@7647
   988
            --     v_Offer_ID := M_GET_OFFER(v_DateInvoiced, v_BPartner_ID, CUR_BOM.M_ProductBOM_ID);
gorkaion@7647
   989
            /* INSERT INTO C_INVOICELINE
gorkaion@7647
   990
              (C_InvoiceLine_ID,
gorkaion@7647
   991
               AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,
carlos@0
   992
                C_Invoice_ID,Line,
carlos@0
   993
                Description,
carlos@0
   994
                M_Product_ID,C_UOM_ID,
carlos@0
   995
                QtyInvoiced,
carlos@0
   996
                PriceList,PriceActual,PriceLimit,LineNetAmt,
carlos@0
   997
                C_Charge_ID,ChargeAmt,
carlos@0
   998
                C_Tax_ID,
carlos@0
   999
                PriceStd)
gorkaion@7647
  1000
              VALUES
carlos@0
  1001
                (v_NextNo,
carlos@0
  1002
                CUR_BOM_Line.AD_Client_ID,CUR_BOM_Line.AD_Org_ID,CUR_BOM_Line.IsActive,now(),v_UpdatedBy,now(),v_UpdatedBy,
carlos@0
  1003
                CUR_BOM_Line.C_Invoice_ID,v_Line,
carlos@0
  1004
                CUR_BOM.Description,
carlos@0
  1005
                CUR_BOM.M_ProductBOM_ID, CUR_BOM.C_UOM_ID,
carlos@0
  1006
                CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty,
gorkaion@1787
  1007
                M_BOM_PriceList(CUR_BOM.M_ProductBOM_ID, PriceList_Version_ID),M_GET_OFFER_PRICE(v_Offer_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, PriceList_Version_ID)td),
gorkaion@1787
  1008
                M_BOM_PriceLimit(CUR_BOM.M_ProductBOM_ID, PriceList_Version_ID),
gorkaion@1787
  1009
                M_GET_OFFER_PRICE(v_Offer_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, PriceList_Version_ID)) * CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty,
carlos@0
  1010
                CUR_BOM_Line.C_Charge_ID,v_ChargeAmt,
carlos@0
  1011
                CUR_BOM_Line.C_Tax_ID);
carlos@0
  1012
                */
gorkaion@7647
  1013
            -- M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, PriceList_Version_ID), v_Offer_ID);
gorkaion@7647
  1014
            -- One Time variables
gorkaion@7647
  1015
            INSERT INTO C_INVOICELINE
carlos@0
  1016
              (
gorkaion@7647
  1017
               C_InvoiceLine_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@7647
  1018
               Created, CreatedBy, Updated, UpdatedBy,
gorkaion@7647
  1019
               C_Invoice_ID, Line, Description, M_Product_ID,
gorkaion@7647
  1020
               C_UOM_ID, QtyInvoiced, PriceList,
gorkaion@7647
  1021
               PriceActual,
gorkaion@7647
  1022
               PriceLimit, LineNetAmt, C_Charge_ID, ChargeAmt,
gorkaion@7647
  1023
               C_Tax_ID, PriceStd
carlos@0
  1024
              )
carlos@0
  1025
              VALUES
carlos@0
  1026
              (
gorkaion@7647
  1027
               get_uuid(), CUR_BOM_Line.AD_Client_ID, CUR_BOM_Line.AD_Org_ID, CUR_BOM_Line.IsActive,
gorkaion@7647
  1028
               now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7647
  1029
               CUR_BOM_Line.C_Invoice_ID, v_Line, CUR_BOM.Description, CUR_BOM.M_ProductBOM_ID,
gorkaion@7647
  1030
               CUR_BOM.C_UOM_ID, CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, M_BOM_PriceList(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID),
gorkaion@7647
  1031
               M_Get_Offers_Price(v_DateInvoiced, v_BPartner_ID, CUR_BOM.M_ProductBOM_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID),CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, v_PriceList_ID),
gorkaion@7647
  1032
               M_BOM_PriceLimit(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID),
gorkaion@7647
  1033
               M_Get_Offers_Price(v_DateInvoiced, v_BPartner_ID, CUR_BOM.M_ProductBOM_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID),CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, v_PriceList_ID) * CUR_BOM_Line.QtyInvoiced*CUR_BOM.BOMQty, CUR_BOM_Line.C_Charge_ID, v_ChargeAmt,
gorkaion@7647
  1034
               CUR_BOM_Line.C_Tax_ID, M_BOM_PriceStd(CUR_BOM.M_ProductBOM_ID, v_PriceList_Version_ID)
gorkaion@7647
  1035
              );
gorkaion@7647
  1036
            v_ChargeAmt:=0;
gorkaion@7647
  1037
          END LOOP; -- Create New Lines
gorkaion@7647
  1038
          -- Convert into Comment Line
gorkaion@7647
  1039
          UPDATE C_INVOICELINE
gorkaion@7647
  1040
          SET M_Product_ID=NULL,
gorkaion@7647
  1041
              PriceList=0,
gorkaion@7647
  1042
              PriceActual=0,
gorkaion@7647
  1043
              PriceLimit=0,
gorkaion@7647
  1044
              LineNetAmt=0,
gorkaion@7647
  1045
              ChargeAmt=0,
gorkaion@7647
  1046
              Description=
gorkaion@7647
  1047
                (SELECT p.NAME || ' ' || C_INVOICELINE.Description
gorkaion@7647
  1048
                 FROM M_PRODUCT p
gorkaion@7647
  1049
                 WHERE p.M_Product_ID=CUR_BOM_Line.M_Product_ID
gorkaion@7647
  1050
                ),
gorkaion@7647
  1051
              PriceStd=0,
gorkaion@7647
  1052
              M_Offer_ID=NULL
gorkaion@7647
  1053
          WHERE C_InvoiceLine_ID=CUR_BOM_Line.C_InvoiceLine_ID;
gorkaion@7647
  1054
        END LOOP; -- Replace Lines
gorkaion@7647
  1055
      END LOOP; -- BOM Loop
gorkaion@7647
  1056
    END;
gorkaion@7647
  1057
  END IF;--FINISH_PROCESS
gorkaion@7647
  1058
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
  1059
    /**************************************************************************
gorkaion@7647
  1060
     * Calculate Discounts
gorkaion@7647
  1061
     *************************************************************************/
gorkaion@7647
  1062
    v_CumDiscount:=0;
gorkaion@7647
  1063
    v_OldCumDiscount:=0;
gorkaion@7647
  1064
    v_Line:=10;
gorkaion@7647
  1065
    SELECT MAX(LINE) + 10 INTO v_InvoiceLineSeqNo
gorkaion@7647
  1066
    FROM C_INVOICELINE
gorkaion@7647
  1067
    WHERE C_INVOICE_ID=v_Record_ID;
gorkaion@7647
  1068
    FOR Cur_CInvoiceDiscount IN
gorkaion@7647
  1069
      (SELECT C_INVOICE_DISCOUNT.C_INVOICE_DISCOUNT_ID, C_DISCOUNT.DISCOUNT, C_DISCOUNT.M_PRODUCT_ID, C_DISCOUNT.NAME,
gorkaion@7647
  1070
           C_INVOICE_DISCOUNT.CASCADE, C_DISCOUNT.C_DISCOUNT_ID, M_PRODUCT.C_UOM_ID
gorkaion@7647
  1071
       FROM C_INVOICE_DISCOUNT, C_DISCOUNT, M_PRODUCT
gorkaion@7647
  1072
       WHERE C_INVOICE_DISCOUNT.C_DISCOUNT_ID=C_DISCOUNT.C_DISCOUNT_ID
gorkaion@7647
  1073
         AND C_DISCOUNT.M_PRODUCT_ID=M_PRODUCT.M_PRODUCT_ID
gorkaion@7647
  1074
         AND C_INVOICE_DISCOUNT.C_INVOICE_ID=v_Record_ID
gorkaion@7647
  1075
         AND C_INVOICE_DISCOUNT.ISACTIVE='Y'
gorkaion@7647
  1076
       ORDER BY C_INVOICE_DISCOUNT.LINE
gorkaion@7647
  1077
      )
gorkaion@7647
  1078
    LOOP
gorkaion@7647
  1079
      v_CumDiscount:=(1-v_OldCumDiscount) * Cur_CInvoiceDiscount.Discount/100;
gorkaion@7647
  1080
      v_OldCumDiscount:=v_OldCumDiscount + v_CumDiscount;
gorkaion@7647
  1081
      FOR Cur_TaxDiscount IN
gorkaion@7647
  1082
        (SELECT C_INVOICELINE.C_TAX_ID, SUM(C_INVOICELINE.LINENETAMT) AS LINENETAMT
gorkaion@7647
  1083
         FROM C_INVOICELINE
gorkaion@7647
  1084
         WHERE C_INVOICE_ID=v_Record_ID
gorkaion@7647
  1085
           AND C_INVOICELINE.LINENETAMT<>0
gorkaion@7647
  1086
           AND C_INVOICE_DISCOUNT_ID IS NULL
gorkaion@7647
  1087
         GROUP BY C_TAX_ID
gorkaion@7647
  1088
        )
gorkaion@7647
  1089
      LOOP
gorkaion@7647
  1090
        IF (Cur_CInvoiceDiscount.CASCADE='Y') THEN
gorkaion@7647
  1091
          v_Discount:=(-1) * Cur_TaxDiscount.LINENETAMT * v_CumDiscount;
gorkaion@7647
  1092
        ELSE
gorkaion@7647
  1093
          v_Discount:=(-1) * Cur_TaxDiscount.LINENETAMT * Cur_CInvoiceDiscount.Discount/100;
gorkaion@7647
  1094
        END IF;
gorkaion@7647
  1095
        v_InvoiceLineSeqNo:=10 + v_InvoiceLineSeqNo;
gorkaion@7647
  1096
        v_InvoiceLine:=get_uuid();
gorkaion@7647
  1097
        INSERT INTO C_INVOICELINE
gorkaion@7647
  1098
          (
gorkaion@7647
  1099
           C_INVOICELINE_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE,
gorkaion@7647
  1100
           CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@7647
  1101
           C_INVOICE_ID, C_ORDERLINE_ID, M_INOUTLINE_ID, LINE,
gorkaion@7647
  1102
           DESCRIPTION, M_PRODUCT_ID, QTYINVOICED, PRICELIST,
gorkaion@7647
  1103
           PRICEACTUAL, PRICELIMIT, LINENETAMT, C_CHARGE_ID,
gorkaion@7647
  1104
           CHARGEAMT, C_UOM_ID, C_TAX_ID, S_RESOURCEASSIGNMENT_ID,
gorkaion@7647
  1105
           TAXAMT, M_ATTRIBUTESETINSTANCE_ID, ISDESCRIPTION,
gorkaion@7647
  1106
           QUANTITYORDER, M_PRODUCT_UOM_ID, PRICESTD
gorkaion@7647
  1107
          )
gorkaion@7647
  1108
          VALUES
gorkaion@7647
  1109
          (
gorkaion@7647
  1110
           v_InvoiceLine, v_Client_ID, v_Org_ID, 'Y',
gorkaion@7647
  1111
           now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7647
  1112
           v_Record_ID, NULL, NULL, v_InvoiceLineSeqNo,
gorkaion@7647
  1113
           Cur_CInvoiceDiscount.NAME, Cur_CInvoiceDiscount.M_PRODUCT_ID, 1, v_Discount,
gorkaion@7647
  1114
           v_Discount, v_Discount, v_Discount, NULL,
gorkaion@7647
  1115
           0, Cur_CInvoiceDiscount.C_UOM_ID, Cur_TaxDiscount.C_TAX_ID, NULL,
gorkaion@7647
  1116
           NULL, NULL, 'N' ,
gorkaion@7647
  1117
           NULL, NULL, v_Discount
gorkaion@7647
  1118
          );
gorkaion@7647
  1119
        --v_InvoiceDiscount:=Ad_Sequence_Nextno('C_InvoiceLine');
gorkaion@7647
  1120
        UPDATE C_INVOICELINE
gorkaion@7647
  1121
        SET C_INVOICE_DISCOUNT_ID=Cur_CInvoiceDiscount.C_INVOICE_DISCOUNT_ID
gorkaion@7647
  1122
        WHERE C_INVOICELINE_ID=v_InvoiceLine;
gorkaion@7647
  1123
      END LOOP;
gorkaion@7647
  1124
      v_Line:=v_Line + 10;
gorkaion@7647
  1125
    END LOOP;
gorkaion@7647
  1126
  END IF;--FINISH_PROCESS
gorkaion@7647
  1127
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
  1128
    /**************************************************************************
gorkaion@7647
  1129
     * Calculate Invoice Taxes and Totals
gorkaion@7647
  1130
     *************************************************************************/
gorkaion@7647
  1131
    DECLARE
gorkaion@7647
  1132
      Cur_Tax RECORD;
gorkaion@7647
  1133
      Cur_MultiTax RECORD;
gorkaion@7647
  1134
      xTaxBaseAmt NUMBER:=0;
gorkaion@7647
  1135
      xTaxAmt NUMBER:=0;
gorkaion@7647
  1136
      v_TaxNoRecalculable NUMBER:=0;
gorkaion@7647
  1137
      v_PreviousTaxAmt NUMBER:=0;
gorkaion@7647
  1138
      HeaderNotAdded BOOLEAN:=TRUE;
gorkaion@7647
  1139
      v_LineNo NUMBER:=0;
gorkaion@7647
  1140
      v_ActualBaseAmt NUMBER;
gorkaion@7647
  1141
      v_FirstLine BOOLEAN;
gorkaion@7647
  1142
      v_C_InvoiceTax_ID VARCHAR2(32);
gorkaion@7647
  1143
    BEGIN
gorkaion@7647
  1144
      v_ResultStr:='DeleteOldTaxes';
gorkaion@7647
  1145
      DELETE FROM C_INVOICELINETAX
gorkaion@7647
  1146
      WHERE C_InvoiceLine_ID IN (SELECT C_InvoiceLine_ID from C_InvoiceLine WHERE C_Invoice_ID = v_Record_ID);
gorkaion@7647
  1147
      DELETE FROM C_INVOICETAX
gorkaion@7647
  1148
      WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
  1149
        AND Recalculate = 'Y';
gorkaion@7647
  1150
      -- For all Tax Rates
gorkaion@7647
  1151
      v_ResultStr:='InsertNewTaxes';
gorkaion@7647
  1152
      FOR Cur_Tax IN
gorkaion@7647
  1153
        (SELECT l.C_InvoiceLine_ID, l.C_Tax_ID, i.IsTaxIncluded,
eduardo@6017
  1154
              COALESCE(SUM(l.LineNetAmt),0) + COALESCE(SUM(l.ChargeAmt), 0) AS LineNetAmt,
eduardo@6017
  1155
              COALESCE(SUM(l.TaxBaseAmt), 0) + COALESCE(SUM(l.ChargeAmt), 0) AS TaxBaseAmt,
carlos@0
  1156
              COALESCE(SUM(i.ChargeAmt), 0) AS HeaderNet,
gorkaion@7647
  1157
              t.Rate, t.IsSummary, c.StdPrecision, t.Cascade, t.BaseAmount
gorkaion@7647
  1158
         FROM C_INVOICE i, C_INVOICELINE l, C_TAX t, C_CURRENCY c
gorkaion@7647
  1159
         WHERE i.C_Invoice_ID=l.C_Invoice_ID
gorkaion@7647
  1160
           AND i.C_Invoice_ID=v_Record_ID -- Parameter
gorkaion@7647
  1161
           AND l.C_Tax_ID=t.C_Tax_ID
gorkaion@7647
  1162
           AND i.C_Currency_ID=c.C_Currency_ID
gorkaion@7647
  1163
         GROUP BY l.C_InvoiceLine_ID, l.C_Tax_ID,i.IsTaxIncluded, t.Rate, t.IsSummary,
gorkaion@7647
  1164
              c.StdPrecision, t.Cascade, t.BaseAmount
gorkaion@7647
  1165
         ORDER BY 4 DESC
gorkaion@7647
  1166
        )
gorkaion@7647
  1167
      LOOP
gorkaion@7647
  1168
        xTaxBaseAmt:=Cur_Tax.LineNetAmt;
gorkaion@7647
  1169
        v_TotalLines:=v_TotalLines + xTaxBaseAmt; -- w/o Header Freight/Charge
gorkaion@7647
  1170
        IF (HeaderNotAdded) THEN -- add header to first
gorkaion@7647
  1171
          HeaderNotAdded:=FALSE;
gorkaion@7647
  1172
          xTaxBaseAmt:=xTaxBaseAmt + Cur_Tax.HeaderNet;
gorkaion@7647
  1173
        END IF;
gorkaion@7647
  1174
        C_INVOICELINETAX_INSERT(v_Org_ID, v_Record_ID, Cur_Tax.C_InvoiceLine_ID, v_UpdatedBy, Cur_Tax.C_Tax_ID, Cur_Tax.C_Tax_ID, Cur_Tax.LineNetAmt, Cur_Tax.TaxBaseAmt, Cur_Tax.StdPrecision);
gorkaion@7647
  1175
      END LOOP; -- Insert New Taxes
gorkaion@7647
  1176
      -- Update Header
gorkaion@7647
  1177
      SELECT COALESCE(SUM(TaxAmt),0) INTO v_TaxNoRecalculable
gorkaion@7647
  1178
      FROM C_INVOICETAX
gorkaion@7647
  1179
      WHERE C_Invoice_ID = v_Record_ID
gorkaion@7647
  1180
        AND Recalculate = 'N';
sivaraman@7819
  1181
      IF (v_IsSOTrx = 'N') THEN
sivaraman@7819
  1182
        SELECT c_getwithholding(v_record_id) INTO withholdamount FROM dual;
sivaraman@7819
  1183
      ELSE
sivaraman@7819
  1184
        withholdamount:=0;
sivaraman@7819
  1185
      END IF;
carlos@0
  1186
gorkaion@7647
  1187
      v_GrandTotal:=C_Currency_Round(v_GrandTotal+v_TaxNoRecalculable, v_Currency_ID, NULL) ;
gorkaion@7647
  1188
      SELECT COALESCE(SUM(TAXAMT), 0) INTO v_GrandTotal
gorkaion@7647
  1189
      FROM C_INVOICETAX
gorkaion@7647
  1190
      WHERE C_INVOICE_ID = v_Record_ID;
gorkaion@7647
  1191
      v_GrandTotal:=v_GrandTotal+ v_TotalLines;
gorkaion@7647
  1192
      UPDATE C_INVOICE
gorkaion@7647
  1193
      SET TotalLines=v_TotalLines,
gorkaion@7647
  1194
          GrandTotal=v_GrandTotal,
gorkaion@7647
  1195
          withholdingamount = withholdamount
gorkaion@7647
  1196
      WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
  1197
      DBMS_OUTPUT.PUT_LINE('withholdingamount=' || withholdamount);
gorkaion@7647
  1198
      DBMS_OUTPUT.PUT_LINE('GrandTotal=' || v_GrandTotal) ;
gorkaion@7647
  1199
    END; -- Calculate Tax and Totals
gorkaion@7647
  1200
    -- Synchronize Client/Org Ownership
gorkaion@7647
  1201
    v_ResultStr:='SyncOwnershipClient';
gorkaion@7647
  1202
    UPDATE C_INVOICELINE
gorkaion@7647
  1203
    SET AD_Client_ID=v_Client_ID
gorkaion@7647
  1204
    WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
  1205
      AND AD_Client_ID<>v_Client_ID;
gorkaion@7647
  1206
    v_ResultStr:='SyncOwnershipOrg';
gorkaion@7647
  1207
    UPDATE C_INVOICELINE
gorkaion@7647
  1208
    SET AD_Org_ID=v_Org_ID
gorkaion@7647
  1209
    WHERE C_Invoice_ID=v_Record_ID
gorkaion@7647
  1210
      AND C_Charge_ID IS NULL -- sync for products
gorkaion@7647
  1211
      AND AD_Org_ID<>v_Org_ID;
gorkaion@7647
  1212
  END IF;--FINISH_PROCESS
gorkaion@7647
  1213
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
  1214
    /**************************************************************************
gorkaion@7647
  1215
     * Update BP Statistics
gorkaion@7647
  1216
     *************************************************************************/
gorkaion@7647
  1217
    v_ResultStr:='Updating BPartners';
gorkaion@7647
  1218
    -- First Sale
gorkaion@7647
  1219
    UPDATE C_BPARTNER
gorkaion@7647
  1220
    SET FirstSale=v_DateAcct
gorkaion@7647
  1221
    WHERE C_BPartner_ID=v_BPartner_ID
gorkaion@7647
  1222
      AND FirstSale IS NULL;
gorkaion@7647
  1223
    -- Last Contact, Result
gorkaion@7647
  1224
    UPDATE AD_USER
gorkaion@7647
  1225
    SET LastContact=now(),
gorkaion@7647
  1226
        LastResult=v_DocumentNo
gorkaion@7647
  1227
    WHERE AD_User_ID=v_BPartner_User_ID;
gorkaion@7647
  1228
    -- Update total revenue and credit limit
gorkaion@7647
  1229
    -- It is reversed in C_Allocation_Trg
gorkaion@7647
  1230
    IF (v_IsSOTrx='Y') THEN
gorkaion@7647
  1231
      UPDATE C_BPARTNER
gorkaion@7647
  1232
      SET ActualLifeTimeValue=ActualLifeTimeValue +(v_Multiplier *  C_Base_Convert(v_GrandTotal, v_Currency_ID, v_Client_ID, v_DateAcct, v_Org_ID))
gorkaion@7647
  1233
      WHERE C_BPartner_ID=v_BPartner_ID;
gorkaion@7647
  1234
    END IF;
gorkaion@7647
  1235
  END IF;--FINISH_PROCESS
gorkaion@7647
  1236
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
  1237
    /**************************************************************************
gorkaion@7647
  1238
     * Matching
gorkaion@7647
  1239
     *************************************************************************/
gorkaion@7647
  1240
    v_ResultStr:='Matching';
gorkaion@7647
  1241
    IF (v_IsSOTrx='N') THEN
gorkaion@7647
  1242
      DECLARE
gorkaion@7647
  1243
        -- Invoice-Receipt Match
gorkaion@7647
  1244
        Cur_ILines_Receipt RECORD;
gorkaion@7647
  1245
        -- Invoice-PO Match
gorkaion@7647
  1246
        Cur_ILines_PO RECORD;
gorkaion@7647
  1247
        v_Qty NUMBER;
gorkaion@7647
  1248
        v_MatchInv_ID VARCHAR2(32) ;
gorkaion@7647
  1249
        v_MatchPO_ID VARCHAR2(32) ;
gorkaion@7647
  1250
      BEGIN
gorkaion@7647
  1251
        v_ResultStr:='MatchInv-Receipt';
gorkaion@7647
  1252
        FOR Cur_ILines_Receipt IN
gorkaion@7647
  1253
          (SELECT il.AD_Client_ID, il.AD_Org_ID, il.C_InvoiceLine_ID, ml.M_InOutLine_ID,
gorkaion@7647
  1254
               ml.M_Product_ID, ml.MovementQty, il.QtyInvoiced, i.DateAcct
gorkaion@7647
  1255
           FROM C_INVOICELINE il
gorkaion@7647
  1256
                INNER JOIN M_INOUTLINE ml ON (il.M_InOutLine_ID=ml.M_InOutLine_ID)
gorkaion@7647
  1257
                INNER JOIN C_INVOICE i ON(il.C_Invoice_ID=i.C_Invoice_ID)
gorkaion@7647
  1258
           WHERE il.M_Product_ID=ml.M_Product_ID
gorkaion@7647
  1259
             AND il.C_Invoice_ID=v_Record_ID
gorkaion@7647
  1260
           )
gorkaion@7647
  1261
        LOOP
gorkaion@7647
  1262
          IF (Cur_ILines_Receipt.M_INOUTLINE_ID IS NOT NULL) THEN
gorkaion@7647
  1263
            SELECT COUNT(1) INTO v_Count
gorkaion@7647
  1264
            FROM M_MATCHINV
gorkaion@7647
  1265
            WHERE C_INVOICELINE_ID=Cur_ILines_Receipt.C_InvoiceLine_ID
gorkaion@7647
  1266
              AND M_INOUTLINE_ID=Cur_ILines_Receipt.M_INOUTLINE_ID;
gorkaion@7647
  1267
            IF (v_Count=0) THEN
gorkaion@7647
  1268
              v_Qty:=Cur_ILines_Receipt.QtyInvoiced;
gorkaion@7647
  1269
              v_MatchInv_ID := get_uuid();
gorkaion@7647
  1270
              v_ResultStr:='InsertMatchInv ' || v_MatchInv_ID;
gorkaion@7647
  1271
              DBMS_OUTPUT.PUT_LINE('  M_MatchInv_ID=' || v_MatchInv_ID || ' - ' || v_Qty) ;
gorkaion@7647
  1272
              INSERT INTO M_MATCHINV
carlos@0
  1273
                (
gorkaion@7647
  1274
                 M_MatchInv_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@7647
  1275
                 Created, CreatedBy, Updated, UpdatedBy,
gorkaion@7647
  1276
                 M_InOutLine_ID, C_InvoiceLine_ID, M_Product_ID, DateTrx,
gorkaion@7647
  1277
                 Qty, Processing, Processed, Posted
carlos@0
  1278
                )
carlos@0
  1279
                VALUES
carlos@0
  1280
                (
gorkaion@7647
  1281
                 v_MatchInv_ID, Cur_ILines_Receipt.AD_Client_ID, Cur_ILines_Receipt.AD_Org_ID, 'Y',
gorkaion@7647
  1282
                 now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7647
  1283
                 Cur_ILines_Receipt.M_InOutLine_ID, Cur_ILines_Receipt.C_InvoiceLine_ID, Cur_ILines_Receipt.M_Product_ID, Cur_ILines_Receipt.DateAcct,
gorkaion@7647
  1284
                 v_Qty, 'N', 'Y', 'N'
gorkaion@7647
  1285
                );
gorkaion@7647
  1286
            END IF;
gorkaion@7647
  1287
          END IF;
gorkaion@7647
  1288
        END LOOP;
gorkaion@7647
  1289
        v_ResultStr:='MatchInv-PO';
gorkaion@7647
  1290
        FOR Cur_ILines_PO IN
gorkaion@7647
  1291
          (SELECT il.AD_Client_ID, il.AD_Org_ID, il.C_InvoiceLine_ID, ol.C_OrderLine_ID,
gorkaion@7647
  1292
               ol.M_Product_ID, ol.C_Charge_ID, ol.QtyOrdered, il.QtyInvoiced,
gorkaion@7647
  1293
                i.DateAcct
gorkaion@7647
  1294
           FROM C_INVOICELINE il
gorkaion@7647
  1295
                INNER JOIN C_ORDERLINE ol ON (il.C_OrderLine_ID=ol.C_OrderLine_ID)
gorkaion@7647
  1296
                INNER JOIN C_INVOICE i ON (il.C_Invoice_ID=i.C_Invoice_ID)
gorkaion@7647
  1297
           WHERE (il.M_Product_ID=ol.M_Product_ID
gorkaion@7647
  1298
                  OR il.C_Charge_ID=ol.C_Charge_ID)
gorkaion@7647
  1299
             AND il.C_Invoice_ID=v_Record_ID
gorkaion@7647
  1300
          )
gorkaion@7647
  1301
        LOOP
gorkaion@7647
  1302
          -- The min qty. Modified by Ismael Ciordia
gorkaion@7647
  1303
          --v_Qty := Cur_ILines_PO.QtyOrdered;
gorkaion@7647
  1304
          --IF (ABS(Cur_ILines_PO.QtyOrdered) > ABS(Cur_ILines_PO.QtyInvoiced)) THEN
gorkaion@7647
  1305
          v_Qty:=Cur_ILines_PO.QtyInvoiced;
gorkaion@7647
  1306
          --END IF;
gorkaion@7647
  1307
          v_MatchPO_ID := get_uuid();
gorkaion@7647
  1308
          v_ResultStr:='InsertMatchPO ' || v_MatchPO_ID;
gorkaion@7647
  1309
          DBMS_OUTPUT.PUT_LINE('  M_MatchPO_ID=' || v_MatchPO_ID || ' - ' || v_Qty) ;
gorkaion@7647
  1310
          INSERT INTO M_MATCHPO
gorkaion@7647
  1311
            (
gorkaion@7647
  1312
             M_MatchPO_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@7647
  1313
             Created, CreatedBy, Updated, UpdatedBy,
gorkaion@7647
  1314
             C_OrderLine_ID, M_InOutLine_ID, C_InvoiceLine_ID, M_Product_ID,
gorkaion@7647
  1315
             DateTrx, Qty, Processing, Processed,
gorkaion@7647
  1316
             Posted
gorkaion@7647
  1317
            )
gorkaion@7647
  1318
            VALUES
gorkaion@7647
  1319
            (
gorkaion@7647
  1320
             v_MatchPO_ID, Cur_ILines_PO.AD_Client_ID, Cur_ILines_PO.AD_Org_ID, 'Y',
gorkaion@7647
  1321
             now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7647
  1322
             Cur_ILines_PO.C_OrderLine_ID, NULL, Cur_ILines_PO.C_InvoiceLine_ID, Cur_ILines_PO.M_Product_ID,
gorkaion@7647
  1323
             Cur_ILines_PO.DateAcct, v_Qty, 'N', 'Y',
gorkaion@7647
  1324
             'N'
gorkaion@7647
  1325
            );
gorkaion@7647
  1326
        END LOOP;
gorkaion@7647
  1327
      END;
gorkaion@7647
  1328
    ELSE -- Actualiza las cantidades facturadas de los pedidos de venta, y las lineas de albaryn facturadas
gorkaion@7647
  1329
      DECLARE
gorkaion@7647
  1330
        CurLines RECORD;
gorkaion@7647
  1331
        p_DateInvoiced DATE;
gorkaion@7647
  1332
        v_totalQtyInvoiced NUMBER;
gorkaion@7647
  1333
        v_ODocumentNo C_ORDER.DocumentNo%TYPE;
gorkaion@7647
  1334
        v_NewPendingToInvoice NUMBER;
gorkaion@7647
  1335
        v_deliveredQty NUMBER;
gorkaion@7647
  1336
        v_inOutStatus varchar2(60) ;
gorkaion@7647
  1337
      BEGIN
gorkaion@7647
  1338
        SELECT DateInvoiced
gorkaion@7647
  1339
        INTO p_DateInvoiced
gorkaion@7647
  1340
        FROM C_INVOICE
gorkaion@7647
  1341
        WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
  1342
        FOR CurLines IN
gorkaion@7647
  1343
          (SELECT * FROM C_INVOICELINE  WHERE C_INVOICE_ID=v_Record_ID  ORDER BY line)
gorkaion@7647
  1344
        LOOP
gorkaion@7647
  1345
          IF (CurLines.C_OrderLine_ID IS NOT NULL) THEN
gorkaion@7647
  1346
            --Check that qty pending to invoice is higher or equal to the qty being invoiced
gorkaion@7647
  1347
            SELECT o.documentno, ABS(ol.qtyordered) - ABS(ol.qtyinvoiced + CurLines.QtyInvoiced)
gorkaion@7647
  1348
              INTO v_ODocumentNo, v_NewPendingToInvoice
gorkaion@7647
  1349
            FROM c_order o, c_orderline ol
gorkaion@7647
  1350
            WHERE o.c_order_id = ol.c_order_id
gorkaion@7647
  1351
              AND ol.c_orderline_id = CurLines.c_orderline_id;
gorkaion@7647
  1352
            IF (v_NewPendingToInvoice <0 ) THEN
gorkaion@7647
  1353
              v_Message := '@NotPossibleCompleteInvoice@' || ' ' || v_DocumentNo;
gorkaion@7647
  1354
              v_Message := v_Message || ' ' || '@line@' || ' ' || CurLines.line || '. ';
gorkaion@7647
  1355
              v_Message := v_Message || '@OrderDocumentno@' || ' ' || v_ODocumentNo;
gorkaion@7647
  1356
              v_Message := v_Message || ': ' || '@QtyInvoicedHigherOrdered@' || '.';
gorkaion@7647
  1357
              RAISE_APPLICATION_ERROR(-20000, v_Message);
gorkaion@7647
  1358
            END IF;
gorkaion@7647
  1359
            UPDATE C_ORDERLINE
gorkaion@7647
  1360
            SET QtyInvoiced=QtyInvoiced + CurLines.QtyInvoiced,
gorkaion@7647
  1361
                DateInvoiced=p_DateInvoiced,
gorkaion@7647
  1362
                Updated=now(),
gorkaion@7647
  1363
                UpdatedBy=v_UpdatedBy
gorkaion@7647
  1364
            WHERE C_OrderLine_ID=CurLines.C_OrderLine_ID;
gorkaion@7647
  1365
          END IF;
gorkaion@7647
  1366
          IF (CurLines.M_InOutLine_ID IS NOT NULL) THEN
gorkaion@7647
  1367
            SELECT m.DOCSTATUS INTO v_inOutStatus
gorkaion@7647
  1368
            FROM M_INOUT m, M_INOUTLINE ml
gorkaion@7647
  1369
            WHERE M.M_InOut_ID=ml.M_InOut_ID
gorkaion@7647
  1370
              AND ml.M_InOutLine_ID=CurLines.M_InOutLine_ID;
gorkaion@7647
  1371
            IF (v_inOutStatus<>'RE') THEN
gorkaion@7647
  1372
              SELECT COALESCE(SUM(C_INVOICELINE.QTYINVOICED), 0) INTO v_totalQtyInvoiced
gorkaion@7647
  1373
              FROM C_INVOICELINE, C_INVOICE
gorkaion@7647
  1374
              WHERE C_INVOICE.C_Invoice_ID=C_INVOICELINE.C_Invoice_ID
gorkaion@7647
  1375
                AND C_INVOICE.Processed='Y'
gorkaion@7647
  1376
                AND C_INVOICELINE.M_InOutLine_ID=CurLines.M_InOutLine_ID;
gorkaion@7647
  1377
              v_totalQtyInvoiced:=v_totalQtyInvoiced + CurLines.QtyInvoiced;
gorkaion@7647
  1378
              SELECT MovementQty INTO v_deliveredQty
gorkaion@7647
  1379
              FROM M_INOUTLINE
gorkaion@7647
  1380
              WHERE M_InOutLine_ID=CurLines.M_InOutLine_ID;
gorkaion@7647
  1381
              UPDATE M_INOUTLINE
gorkaion@7647
  1382
              SET IsInvoiced=(
carlos@0
  1383
                    CASE v_totalQtyInvoiced
gorkaion@7647
  1384
                      WHEN 0 THEN 'N'
carlos@0
  1385
                      ELSE 'Y'
gorkaion@7647
  1386
                    END)
gorkaion@7647
  1387
              WHERE M_InOutLine_ID=CurLines.M_InOutLine_ID;
gorkaion@7647
  1388
            END IF;
antonio@737
  1389
          END IF;
gorkaion@7647
  1390
        END LOOP;
gorkaion@4437
  1391
      END;
gorkaion@4437
  1392
    END IF;
gorkaion@7647
  1393
  END IF;--FINISH_PROCESS
gorkaion@7647
  1394
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
  1395
    -- Modified by Ismael Ciordia
gorkaion@7647
  1396
    -- Generate C_Debt_Payment linked to this invoice
gorkaion@7647
  1397
    DECLARE
gorkaion@7647
  1398
      v_totalCash NUMBER:=0;
gorkaion@7647
  1399
      v_processed CHAR(1):='N';
gorkaion@7647
  1400
      v_debtPaymentID varchar2(32) ;
gorkaion@7647
  1401
      v_amount NUMBER;
gorkaion@7647
  1402
      v_cashBook VARCHAR2(32) ;
gorkaion@7647
  1403
      v_bankAccount VARCHAR2(32) ;
gorkaion@7647
  1404
      v_cash VARCHAR2(32) ;
gorkaion@7647
  1405
      v_IsoCode C_CURRENCY.ISO_CODE%TYPE;
gorkaion@7647
  1406
      v_CashLine VARCHAR2(32) ;
gorkaion@7647
  1407
      v_line NUMBER ;
gorkaion@7647
  1408
      v_BPartnerName C_BPARTNER.NAME%TYPE;
gorkaion@7647
  1409
      v_GenDP_Org VARCHAR2(32);
gorkaion@7648
  1410
      v_dummy VARCHAR2(2000);
gorkaion@7647
  1411
    BEGIN
gorkaion@7648
  1412
      SELECT COUNT(1) INTO v_count
gorkaion@7648
  1413
      FROM ad_preference
gorkaion@7648
  1414
      WHERE property = 'FinancialManagement'
gorkaion@7648
  1415
        AND ad_module_id <> '0';
gorkaion@7648
  1416
      IF (v_count > 1) THEN
gorkaion@7648
  1417
        v_dummy := AD_GET_PREFERENCE_VALUE('FinancialManagement', 'Y', v_client_id, v_org_id, NULL, NULL, NULL);
gorkaion@7648
  1418
      ELSIF (v_count = 0) THEN
gorkaion@7648
  1419
        v_ResultStr:='Generating C_Debt_Payment';
gorkaion@7648
  1420
        UPDATE C_DEBT_PAYMENT
gorkaion@7648
  1421
          SET C_INVOICE_ID=v_Record_ID
gorkaion@7648
  1422
        WHERE EXISTS
gorkaion@7648
  1423
              (SELECT 1
gorkaion@7648
  1424
               FROM C_ORDERLINE ol, C_INVOICELINE il
gorkaion@7648
  1425
               WHERE ol.C_ORDERLINE_ID=il.C_ORDERLINE_ID
gorkaion@7648
  1426
                 AND il.C_INVOICE_ID=v_Record_ID
gorkaion@7648
  1427
                 AND ol.C_ORDER_ID=C_DEBT_PAYMENT.C_ORDER_ID
gorkaion@7648
  1428
              )
gorkaion@7648
  1429
          AND C_INVOICE_ID IS NULL;
gorkaion@7648
  1430
        UPDATE C_DEBT_PAYMENT
gorkaion@7648
  1431
          SET IsValid='Y'
gorkaion@7648
  1432
        WHERE C_INVOICE_ID=v_Record_ID
gorkaion@7648
  1433
          AND IsValid!='Y';
gorkaion@4437
  1434
gorkaion@7648
  1435
        -- Is it a Credit Memo:4
gorkaion@7648
  1436
        SELECT DocBaseType INTO v_TargetDocBaseType
gorkaion@7648
  1437
        FROM C_DOCTYPE
gorkaion@7648
  1438
        WHERE C_DocType_ID=v_DocTypeTarget_ID;
gorkaion@7648
  1439
        IF (v_TargetDocBaseType in ('ARC','APC')) THEN
gorkaion@7648
  1440
          v_MultiplierARC:=-1;
gorkaion@7648
  1441
        END IF;
gorkaion@7648
  1442
gorkaion@7648
  1443
        --Sums debt payments from the order and the ones that have been inserted manually, added by ALO
gorkaion@7648
  1444
        SELECT COALESCE(SUM(C_Currency_Round(C_Currency_Convert((Amount + WriteOffAmt)*v_MultiplierARC, C_Currency_ID, v_Currency_ID, v_DateInvoiced, NULL, v_Client_ID, v_Org_ID), v_Currency_ID, NULL)), 0) INTO v_totalCash
gorkaion@7648
  1445
        FROM C_DEBT_PAYMENT_V dp
gorkaion@7648
  1446
        WHERE C_INVOICE_ID=v_Record_ID;
gorkaion@7648
  1447
        --Insert C_Debt_Payment if GrandTotal - v_totalCash <> 0;
gorkaion@7648
  1448
        IF (v_GrandTotal<>v_totalCash) THEN
gorkaion@7648
  1449
          DECLARE
gorkaion@7648
  1450
            CUR_PAYMENTS RECORD;
gorkaion@7648
  1451
            v_plannedDate DATE;
gorkaion@7648
  1452
            v_pendingAmount NUMBER;
gorkaion@7648
  1453
            v_paymentAmount NUMBER;
gorkaion@7648
  1454
            v_GenDebt_PaymentID varchar2(32);
gorkaion@7648
  1455
            v_SettlementDocTypeID varchar2(32) ;
gorkaion@7648
  1456
            v_settlement_ID VARCHAR2(32) ;
gorkaion@7648
  1457
            v_CB_Curr VARCHAR2(32) ;
gorkaion@7648
  1458
            v_SDocument_No C_SETTLEMENT.DocumentNo%TYPE;
gorkaion@7648
  1459
          BEGIN
gorkaion@7648
  1460
            IF (v_IsSOTrx ='Y') THEN
gorkaion@7648
  1461
              v_pendingAmount:=v_GrandTotal - v_totalCash;
gorkaion@7648
  1462
            ELSE
gorkaion@7648
  1463
              v_pendingAmount:=v_GrandTotal + v_totalCash;
gorkaion@7648
  1464
            END IF;
gorkaion@7648
  1465
            FOR CUR_PAYMENTS IN
gorkaion@7648
  1466
              (SELECT LINE, PERCENTAGE, ONREMAINDER, EXCLUDETAX,
gorkaion@7648
  1467
                   COALESCE(PAYMENTRULE, v_PaymentRule) AS PAYMENTRULE, FIXMONTHDAY, FIXMONTHDAY2, FIXMONTHDAY3,
gorkaion@7648
  1468
                   NETDAYS, FIXMONTHOFFSET, NETDAY, ISNEXTBUSINESSDAY
gorkaion@7648
  1469
               FROM C_PAYMENTTERMLINE
gorkaion@7648
  1470
               WHERE C_PAYMENTTERM_ID=v_PaymentTerm
gorkaion@7648
  1471
               UNION
gorkaion@7648
  1472
               -- Header of paymentTerm is processed at last
gorkaion@7648
  1473
               SELECT 9999 AS LINE, 100 AS PERCENTAGE, 'Y' AS ONREMAINDER, 'N' AS EXCLUDETAX,
gorkaion@7648
  1474
                   v_PaymentRule AS PAYMENTRULE, FIXMONTHDAY, FIXMONTHDAY2, FIXMONTHDAY3,
gorkaion@7648
  1475
                   NETDAYS, FIXMONTHOFFSET, NETDAY, ISNEXTBUSINESSDAY
gorkaion@7648
  1476
               FROM C_PAYMENTTERM
gorkaion@7648
  1477
               WHERE C_PAYMENTTERM_ID=v_PaymentTerm
gorkaion@7648
  1478
               ORDER BY LINE
gorkaion@7648
  1479
              )
gorkaion@7648
  1480
            LOOP
gorkaion@7648
  1481
              IF (CUR_PAYMENTS.PaymentRule IN('B', 'C')) THEN
gorkaion@7648
  1482
                SELECT MAX(C_CashBook_ID) INTO v_cashBook
gorkaion@7648
  1483
                FROM C_CASHBOOK
gorkaion@7648
  1484
                WHERE AD_Client_ID=v_Client_ID
gorkaion@7648
  1485
                  AND isActive='Y'
gorkaion@7648
  1486
                  AND isDefault='Y'
gorkaion@7648
  1487
                  AND AD_IsOrgIncluded(v_org_id,AD_ORG_ID, AD_Client_ID)<>-1;
gorkaion@7648
  1488
                IF (v_cashBook IS NULL) THEN
gorkaion@7648
  1489
                  RAISE_APPLICATION_ERROR(-20000, '@NoDefaultCashBook@');
gorkaion@7648
  1490
                END IF;
gorkaion@7648
  1491
                v_bankAccount:=NULL;
gorkaion@7648
  1492
              ELSE
gorkaion@7648
  1493
                SELECT COALESCE((
gorkaion@7648
  1494
                         CASE v_IsSOTrx
gorkaion@7648
  1495
                           WHEN 'Y' THEN SO_BankAccount_ID
gorkaion@7648
  1496
                           ELSE PO_BankAccount_ID
gorkaion@7648
  1497
                         END
gorkaion@7648
  1498
                         ),
gorkaion@7648
  1499
                         (SELECT MAX(C_BankAccount_ID)
gorkaion@7648
  1500
                          FROM C_BANKACCOUNT
gorkaion@7648
  1501
                          WHERE AD_Client_ID=v_Client_ID
gorkaion@7648
  1502
                            AND isDefault='Y'
gorkaion@7648
  1503
                         )
gorkaion@7648
  1504
                       ) INTO v_bankAccount
gorkaion@7648
  1505
                FROM C_BPARTNER
gorkaion@7648
  1506
                WHERE c_BPartner_ID=v_BPartner_ID;
gorkaion@7648
  1507
                v_cashBook:=NULL;
gorkaion@7648
  1508
              END IF;
gorkaion@7648
  1509
              v_plannedDate:=C_Paymentduedate(v_BPartner_ID, v_IsSOTrx, CUR_PAYMENTS.FixMonthDay, CUR_PAYMENTS.FixMonthDay2, CUR_PAYMENTS.FixMonthDay3, CUR_PAYMENTS.NetDays, CUR_PAYMENTS.FixMonthOffset, CUR_PAYMENTS.NetDay, CUR_PAYMENTS.IsNextbusinessday, v_DateInvoiced) ;
gorkaion@7648
  1510
              SELECT COALESCE(SUM(C_DEBT_PAYMENT_V.AMOUNT),0) INTO v_partialAmount
gorkaion@7648
  1511
              FROM C_DEBT_PAYMENT_V, C_DEBT_PAYMENT
gorkaion@7648
  1512
              WHERE C_DEBT_PAYMENT_V.C_INVOICE_ID = V_RECORD_ID
gorkaion@7648
  1513
                AND C_DEBT_PAYMENT_V.C_DEBT_PAYMENT_ID = C_DEBT_PAYMENT.C_DEBT_PAYMENT_ID
gorkaion@7648
  1514
                AND ISAUTOMATICGENERATED='N';
gorkaion@7648
  1515
              IF (CUR_PAYMENTS.EXCLUDETAX='Y') THEN
gorkaion@7648
  1516
                -- if excludeTax = 'Y', percentage is aplied on the TotalLines
gorkaion@7648
  1517
                v_paymentAmount:=C_Currency_Round((v_TotalLines-v_partialAmount) *CUR_PAYMENTS.PERCENTAGE/100, v_Currency_ID, NULL) ;
gorkaion@7648
  1518
              ELSIF (CUR_PAYMENTS.ONREMAINDER='N') THEN
gorkaion@7648
  1519
                -- if onRemainder = 'N', percentage is aplied on the GrandTotal
gorkaion@7648
  1520
                v_paymentAmount:=C_Currency_Round((v_GrandTotal-v_partialAmount) *CUR_PAYMENTS.PERCENTAGE/100, v_Currency_ID, NULL) ;
gorkaion@7648
  1521
              ELSE
gorkaion@7648
  1522
                v_paymentAmount:=C_Currency_Round((v_pendingAmount) *CUR_PAYMENTS.PERCENTAGE/100, v_Currency_ID, NULL) ;
gorkaion@7648
  1523
              END IF;
gorkaion@7648
  1524
              v_pendingAmount:=v_pendingAmount - v_paymentAmount;
gorkaion@7648
  1525
              v_debtPaymentID :=get_uuid() ;
gorkaion@7648
  1526
              v_paymentcheck:=C_Currency_Round((v_paymentamount *v_multiplierarc) -withholdamount *(v_paymentamount *v_multiplierarc / v_grandtotal), v_Currency_ID, NULL);
gorkaion@7648
  1527
              IF (v_paymentcheck <> 0) THEN
gorkaion@7648
  1528
                INSERT INTO C_DEBT_PAYMENT
gorkaion@7648
  1529
                  (
gorkaion@7648
  1530
                   C_DEBT_PAYMENT_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE,
gorkaion@7648
  1531
                   CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@7648
  1532
                   ISRECEIPT, C_SETTLEMENT_CANCEL_ID, C_SETTLEMENT_GENERATE_ID, DESCRIPTION,
gorkaion@7648
  1533
                   C_INVOICE_ID, C_BPARTNER_ID, C_CURRENCY_ID, C_CASHLINE_ID,
gorkaion@7648
  1534
                   C_BANKACCOUNT_ID, C_CASHBOOK_ID, PAYMENTRULE, ISPAID,
gorkaion@7648
  1535
                   AMOUNT, WRITEOFFAMT, DATEPLANNED, ISMANUAL,
gorkaion@7648
  1536
                   ISVALID, C_BANKSTATEMENTLINE_ID, CHANGESETTLEMENTCANCEL, CANCEL_PROCESSED,
gorkaion@7648
  1537
                   GENERATE_PROCESSED, c_project_id, status, status_initial,   withholdingamount,C_WITHHOLDING_ID
gorkaion@7648
  1538
                  )
gorkaion@7648
  1539
                  VALUES
gorkaion@7648
  1540
                  (
gorkaion@7648
  1541
                   v_debtPaymentID, v_Client_ID, v_Org_ID, 'Y',
gorkaion@7648
  1542
                   now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7648
  1543
                   v_IsSOTrx, NULL, NULL, '* ' || v_DocumentNo || ' * (' || COALESCE(TO_CHAR(v_BPartnerName) ,'') ||( CASE WHEN v_POReference IS NULL THEN '' ELSE ' .Ref:'||TO_CHAR(v_POReference) END) || ' )',
gorkaion@7648
  1544
                   v_Record_ID, v_BPartner_ID, v_Currency_ID, NULL,
gorkaion@7648
  1545
                   v_bankAccount, v_cashBook, CUR_PAYMENTS.PaymentRule, 'N',
gorkaion@7648
  1546
                   C_Currency_Round((v_paymentamount *v_multiplierarc) -withholdamount *(v_paymentamount *v_multiplierarc / v_grandtotal), v_Currency_ID, NULL), 0, v_plannedDate, 'N',
gorkaion@7648
  1547
                   'Y', NULL, 'N', 'N',
gorkaion@7648
  1548
                   'N', v_C_Project_Id, 'DE', 'DE', C_Currency_Round(withholdamount *(v_paymentamount *v_multiplierarc / v_grandtotal), v_Currency_ID, NULL),cWithHoldId
gorkaion@7648
  1549
                  );
gorkaion@7648
  1550
              END IF;
gorkaion@7648
  1551
              --AL
gorkaion@7648
  1552
              --Looking for autogenerated debt-payments
gorkaion@7648
  1553
              SELECT MAX(c_Debt_Payment_Id), MAX(ad_Org_ID)
gorkaion@7648
  1554
                INTO v_GenDebt_PaymentID, v_GenDP_Org
gorkaion@7648
  1555
              FROM C_DEBT_PAYMENT DP
gorkaion@7648
  1556
              WHERE C_BPartner_ID=v_BPartner_ID
gorkaion@7648
  1557
                AND C_Debt_Payment_Status(C_Settlement_Cancel_ID, Cancel_Processed, Generate_Processed, IsPaid, IsValid, C_Cashline_ID, C_BankstatementLine_ID)='P'
gorkaion@7648
  1558
                AND (-1) *Amount=v_paymentAmount
gorkaion@7648
  1559
                AND c_currency_ID=v_Currency_ID
gorkaion@7648
  1560
                AND C_SETTLEMENT_GENERATE_ID IS NOT NULL
gorkaion@7648
  1561
                AND Ad_Isorgincluded(v_Org_id, dp.ad_org_id,v_Client_ID) != -1
gorkaion@7648
  1562
                AND ad_client_id = v_Client_ID
gorkaion@7648
  1563
                AND EXISTS (SELECT 1
gorkaion@7648
  1564
                            FROM C_SETTLEMENT S
gorkaion@7648
  1565
                            WHERE DP.C_SETTLEMENT_GENERATE_ID = S.C_Settlement_ID
gorkaion@7648
  1566
                              AND IsGenerated = 'Y')
gorkaion@7648
  1567
                AND NOT EXISTS (SELECT 1
gorkaion@7648
  1568
                                FROM C_REMITTANCELINE rl
gorkaion@7648
  1569
                                WHERE rl.C_DEBT_PAYMENT_CANCELLED = DP.C_DEBT_PAYMENT_ID);
gorkaion@7648
  1570
  
gorkaion@7648
  1571
              IF (v_GenDebt_PaymentID IS NOT NULL) THEN
gorkaion@7648
  1572
                v_SettlementDocTypeID:=Ad_Get_Doctype(v_Client_ID, v_GenDP_Org, TO_CHAR('STT')) ;
gorkaion@7648
  1573
                v_settlement_ID := get_uuid();
gorkaion@7648
  1574
                Ad_Sequence_Doctype(v_SettlementDocTypeID, v_Record_ID, 'Y', v_SDocument_No) ;
gorkaion@7648
  1575
                IF (v_SDocument_No IS NULL) THEN
gorkaion@7648
  1576
                  Ad_Sequence_Doc('DocumentNo_C_Settlement', v_Client_ID, 'Y', v_SDocument_No) ;
gorkaion@7648
  1577
                END IF;
gorkaion@7648
  1578
                INSERT INTO C_SETTLEMENT
gorkaion@7648
  1579
                  (
gorkaion@7648
  1580
                   C_SETTLEMENT_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE,
gorkaion@7648
  1581
                   CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@7648
  1582
                   DOCUMENTNO, DATETRX, DATEACCT, SETTLEMENTTYPE,
gorkaion@7648
  1583
                   C_DOCTYPE_ID, PROCESSING, PROCESSED, POSTED,
gorkaion@7648
  1584
                   C_CURRENCY_ID, ISGENERATED
gorkaion@7648
  1585
                  )
gorkaion@7648
  1586
                   /*, C_PROJECT_ID, C_CAMPAIGN_ID,
gorkaion@7648
  1587
                   C_ACTIVITY_ID, USER1_ID, USER2_ID, CREATEFROM)*/
gorkaion@7648
  1588
                  VALUES
gorkaion@7648
  1589
                  (
gorkaion@7648
  1590
                   v_Settlement_ID, v_Client_ID, v_GenDP_Org, 'Y',
gorkaion@7648
  1591
                   now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7648
  1592
                   '*C*'||v_SDocument_No, TRUNC(now()), TRUNC(now()), 'C',
gorkaion@7648
  1593
                   v_SettlementDocTypeID, 'N', 'N', 'N',
gorkaion@7648
  1594
                   v_Currency_ID, 'Y'
gorkaion@7648
  1595
                  );
gorkaion@7648
  1596
                UPDATE C_DEBT_PAYMENT
gorkaion@7648
  1597
                SET C_Settlement_Cancel_Id=v_Settlement_ID,
gorkaion@7648
  1598
                    Updated=now(),
gorkaion@7648
  1599
                    UpdatedBy=v_UpdatedBy
gorkaion@7648
  1600
                WHERE c_Debt_Payment_ID IN(v_genDebt_PaymentID, v_debtPaymentID) ;
gorkaion@7648
  1601
                C_SETTLEMENT_POST(NULL, v_Settlement_ID) ;
gorkaion@7648
  1602
              END IF;
gorkaion@7648
  1603
              --If Invoice.paymentRule = 'B', insert de cashline de tipo efecto apuntando al efecto
gorkaion@7648
  1604
              IF (v_cashBook IS NOT NULL AND CUR_PAYMENTS.PaymentRule='B') THEN
gorkaion@7648
  1605
                SELECT MAX(C.C_CASH_ID) INTO v_Cash
gorkaion@7648
  1606
                FROM C_CASH C
gorkaion@7648
  1607
                WHERE C.C_CASHBOOK_ID=v_cashBook
gorkaion@7648
  1608
                  AND TRUNC(C.DATEACCT)=TRUNC(v_DateAcct)
gorkaion@7648
  1609
                  AND C.PROCESSED='N';
gorkaion@7648
  1610
  
gorkaion@7648
  1611
                SELECT C_CURRENCY_ID INTO v_CB_Curr
gorkaion@7648
  1612
                FROM C_CASHBOOK
gorkaion@7648
  1613
                WHERE C_CASHBOOK_ID = v_cashBook;
gorkaion@7648
  1614
  
gorkaion@7648
  1615
                IF (v_Cash IS NULL) THEN
gorkaion@7648
  1616
                  v_ResultStr:='Creating C_Cash';
gorkaion@7648
  1617
                  SELECT ISO_CODE INTO v_IsoCode
gorkaion@7648
  1618
                  FROM C_CURRENCY
gorkaion@7648
  1619
                  WHERE C_Currency_ID=v_CB_Curr;
gorkaion@7648
  1620
                  v_Cash :=get_uuid();
gorkaion@7648
  1621
                  INSERT INTO C_CASH (
gorkaion@7648
  1622
                      C_Cash_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@7648
  1623
                      Created, CreatedBy, Updated, UpdatedBy,
gorkaion@7648
  1624
                      C_CashBook_ID, NAME, StatementDate, DateAcct,
gorkaion@7648
  1625
                      BeginningBalance, EndingBalance, StatementDifference, Processing,
gorkaion@7648
  1626
                      Processed, Posted )
gorkaion@7648
  1627
                    VALUES (
gorkaion@7648
  1628
                      v_Cash, v_Client_ID, v_Org_ID, 'Y',
gorkaion@7648
  1629
                      now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@7648
  1630
                      v_cashBook, (TO_CHAR(v_DateAcct, 'YYYY-MM-DD') || ' ' || v_IsoCode), v_DateAcct, v_DateAcct,
gorkaion@7648
  1631
                      0, 0, 0, 'N',
gorkaion@7648
  1632
                      'N', 'N');
gorkaion@7648
  1633
                END IF; -- v_Cash IS NULL
gorkaion@7648
  1634
                v_ResultStr:='Creating C_CashLine';
gorkaion@7648
  1635
                v_CashLine := get_uuid();
gorkaion@7648
  1636
                SELECT COALESCE(MAX(LINE), 0) + 10 INTO v_line
gorkaion@7648
  1637
                FROM C_CASHLINE
gorkaion@7648
  1638
                WHERE C_CASH_ID=v_Cash;
gorkaion@7648
  1639
  
gorkaion@7648
  1640
                SELECT SUM(AMOUNT) INTO v_Amount
gorkaion@7648
  1641
                FROM C_DEBT_PAYMENT_V
gorkaion@7648
  1642
                WHERE C_INVOICE_ID = v_Record_ID;
gorkaion@7648
  1643
  
gorkaion@7648
  1644
                INSERT INTO C_CASHLINE
gorkaion@7648
  1645
                  (
gorkaion@7648
  1646
                    C_CashLine_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@7648
  1647
                    Created, CreatedBy, Updated, UpdatedBy,
gorkaion@7648
  1648
                    C_Cash_ID, C_Debt_Payment_ID, Line, Description,
gorkaion@7648
  1649
                    Amount, CashType, C_Currency_ID, DiscountAmt,
gorkaion@7648
  1650
                    WriteOffAmt, IsGenerated
gorkaion@7648
  1651
                  )
gorkaion@7648
  1652
                  VALUES
gorkaion@7648
  1653
                  (
gorkaion@7648
  1654
                    v_CashLine, v_Client_ID, v_Org_ID, 'Y',
gorkaion@7648
  1655
                    TO_DATE(now()), v_UpdatedBy, TO_DATE(now()), v_UpdatedBy,
gorkaion@7648
  1656
                    v_Cash, v_debtPaymentID, v_line, v_BPartnerName,
gorkaion@7648
  1657
                    v_Amount, 'P', v_Currency_ID, 0,
gorkaion@7648
  1658
                    0, 'Y'
gorkaion@7648
  1659
                  );
gorkaion@7648
  1660
  
gorkaion@7648
  1661
              END IF; -- v_cashBook IS NOT NULL
gorkaion@7648
  1662
            END LOOP;
gorkaion@7648
  1663
          END;
gorkaion@7648
  1664
        END IF; -- v_GrandTotal <> v_totalCash
gorkaion@7647
  1665
      END IF;
gorkaion@7647
  1666
    END;
gorkaion@7647
  1667
    IF (NOT FINISH_PROCESS AND v_IsSOTrx='Y') THEN
gorkaion@7647
  1668
      C_BP_SOCREDITUSED_REFRESH(v_BPartner_ID) ;
carlos@0
  1669
    END IF;
gorkaion@7647
  1670
  END IF;--FINISH_PROCESS
gorkaion@7647
  1671
  IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@7647
  1672
    -- Finish up -------------------------------------------------------------
gorkaion@7647
  1673
    UPDATE C_INVOICE
gorkaion@7647
  1674
    SET DocStatus='CO',
gorkaion@7647
  1675
        Processed='Y',
gorkaion@7647
  1676
        DocAction='RE',
gorkaion@7647
  1677
        Updated=now(),
gorkaion@7647
  1678
        UpdatedBy=v_UpdatedBy
gorkaion@7647
  1679
    WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
  1680
  END IF;--FINISH_PROCESS
gorkaion@7647
  1681
  IF (NOT FINISH_PROCESS) THEN
gorkaion@7647
  1682
    -- End Processing --------------------------------------------------------
gorkaion@7647
  1683
    --<<END_PROCESSING>>
gorkaion@7647
  1684
    v_ResultStr:='UnLockingInvoice';
gorkaion@7647
  1685
    UPDATE C_INVOICE
gorkaion@7647
  1686
    SET Processing='N',
gorkaion@7647
  1687
        Updated=now(),
gorkaion@7647
  1688
        UpdatedBy=v_UpdatedBy
gorkaion@7647
  1689
    WHERE C_Invoice_ID=v_Record_ID;
gorkaion@7647
  1690
    -- Commented by cromero 19102006 IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@7647
  1691
    -- Commented by cromero 19102006   COMMIT;
gorkaion@7647
  1692
    -- Commented by cromero 19102006 END IF;
gorkaion@7647
  1693
  END IF;--FINISH_PROCESS
gorkaion@7647
  1694
gorkaion@7647
  1695
  --C_Invoice_Post - Finish_Process Extension Point
gorkaion@7647
  1696
  SELECT count(*) INTO v_count FROM DUAL
gorkaion@7647
  1697
  WHERE EXISTS (SELECT 1 FROM ad_ep_procedures WHERE ad_extension_points_id = 'CBE7DD2E561E4D3D8257ECEA5F19687F');
gorkaion@7647
  1698
  IF (v_count=1) THEN
gorkaion@7647
  1699
    DECLARE
gorkaion@7647
  1700
      v_ep_instance VARCHAR2(32);
gorkaion@7647
  1701
      v_extension_point_id VARCHAR2(32) := 'CBE7DD2E561E4D3D8257ECEA5F19687F';
gorkaion@7647
  1702
    BEGIN
gorkaion@7647
  1703
      v_ep_instance := get_uuid();
gorkaion@7647
  1704
      AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Record_ID', v_record_id, NULL, NULL, NULL, NULL, NULL, NULL);
gorkaion@7647
  1705
      AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'DocAction', v_DocAction, NULL, NULL, NULL, NULL, NULL, NULL);
gorkaion@7647
  1706
      AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'User', v_UpdatedBy, NULL, NULL, NULL, NULL, NULL, NULL);
gorkaion@7647
  1707
      AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Message', NULL, NULL, NULL, NULL, NULL, NULL, v_Message);
gorkaion@7647
  1708
      AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Result', NULL, NULL, v_result, NULL, NULL, NULL, NULL);
gorkaion@7647
  1709
      AD_EXTENSION_POINT_HANDLER(v_ep_instance, v_extension_point_id);
gorkaion@7647
  1710
      SELECT p_number INTO v_Result
gorkaion@7647
  1711
      FROM ad_ep_instance_para
gorkaion@7647
  1712
      WHERE ad_ep_instance_id = v_ep_instance
gorkaion@7647
  1713
        AND parametername LIKE 'Result';
gorkaion@7647
  1714
      SELECT p_text INTO v_Message
gorkaion@7647
  1715
      FROM ad_ep_instance_para
gorkaion@7647
  1716
      WHERE ad_ep_instance_id = v_ep_instance
gorkaion@7647
  1717
        AND parametername LIKE 'Message';
gorkaion@7647
  1718
gorkaion@7647
  1719
      DELETE FROM ad_ep_instance_para
gorkaion@7647
  1720
      WHERE ad_ep_instance_id = v_ep_instance;
gorkaion@7647
  1721
    END;
gorkaion@7647
  1722
  END IF;
gorkaion@7647
  1723
harikrishnan@7678
  1724
	FOR Cur_lineqty IN
harikrishnan@7678
  1725
      (SELECT C_INVOICELINE.qtyInvoiced
harikrishnan@7678
  1726
       FROM C_INVOICELINE
harikrishnan@7678
  1727
       WHERE C_Invoice_ID = v_Record_ID
harikrishnan@7678
  1728
      )
harikrishnan@7678
  1729
    LOOP
harikrishnan@7678
  1730
    IF(Cur_lineqty.qtyInvoiced <> 0) THEN
harikrishnan@7678
  1731
      v_totalqty := v_totalqty + 1;
harikrishnan@7678
  1732
     END IF;
harikrishnan@7678
  1733
    END LOOP;
gorkaion@7647
  1734
  --<<FINISH_PROCESS>>
gorkaion@7647
  1735
  IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@7647
  1736
    --  Update AD_PInstance
gorkaion@7647
  1737
    DBMS_OUTPUT.PUT_LINE('Updating PInstance - Finished - ' || v_Message) ;
harikrishnan@7678
  1738
   
harikrishnan@7678
  1739
    IF(v_totalqty = 0 AND v_DocAction <> 'RE') THEN
harikrishnan@7678
  1740
	v_Message := v_Message || '@NoAccountingEntryInvoice@';
harikrishnan@7678
  1741
    END IF;
gorkaion@7647
  1742
    AD_UPDATE_PINSTANCE(p_PInstance_ID, v_UpdatedBy, 'N', v_Result, v_Message) ;
gorkaion@7647
  1743
  ELSE
gorkaion@7647
  1744
    DBMS_OUTPUT.PUT_LINE('--<<C_Invoive_Post finished>> ' || v_Message) ;
gorkaion@7647
  1745
  END IF;
gorkaion@7647
  1746
  RETURN;
gorkaion@7647
  1747
END; --BODY
carlos@0
  1748
EXCEPTION
carlos@0
  1749
WHEN OTHERS THEN
carlos@0
  1750
  DBMS_OUTPUT.PUT_LINE(v_ResultStr) ;
carlos@0
  1751
     v_ResultStr:= '@ERROR=' || SQLERRM;
carlos@0
  1752
      DBMS_OUTPUT.PUT_LINE(v_ResultStr) ;
gorkaion@7647
  1753
      IF (p_PInstance_ID IS NOT NULL) THEN
carlos@0
  1754
        ROLLBACK;
antonio@735
  1755
        AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'N', 0, v_ResultStr) ;
carlos@0
  1756
      ELSE
carlos@1273
  1757
        RAISE;
carlos@1273
  1758
      END IF;
carlos@0
  1759
  -- Commented by cromero 19102006 RETURN;
antonio@735
  1760
END C_INVOICE_POST
gorkaion@239
  1761
]]></body>
carlos@0
  1762
    </function>
adrian@94
  1763
  </database>