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