src-db/database/model/functions/C_INVOICE_POST.xml
author Atul Gaware <atul.gaware@openbravo.com>
Thu, 04 Oct 2018 01:14:57 +0530
changeset 35324 f56c59c75e26
parent 34953 03d8fd2a8cca
permissions -rw-r--r--
Fixes Issue 39386: Goods Shipment IsCompletelyInvoiced
flag is not properly updated when voiding Sales Invoice

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