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