src-db/database/model/functions/C_INVOICE_POST.xml
author Víctor Martínez Romanos <victor.martinez@openbravo.com>
Thu, 28 Nov 2013 11:24:57 +0100
changeset 21513 d35376bf3445
parent 20972 3f5e8c7117d6
child 21626 f64403aac66c
permissions -rw-r--r--
[cashvat] Fixed issue 24615: Cash VAT Management

Any legal entity can define whether it is subscribed to the Cash VAT management. By default organizations
are not subscribed to Cash VAT. To subscribe it, go to Organization | Information and set the Cash VAT flag to Yes.
Since that moment, the Sales flows (orders and invoices) will work with Cash VAT

Vendors can be subscribed to Cash VAT. This can be configured in the ERP at Business Partner | Vendor tab. Note that
each vendor registered into the system may be subscribed to Cash VAT or not.
For Purchase flows (orders and invoices), the system will detect whether the vendor is subscribed to Cash VAT and, in
this case, it will activate the Cash VAT support.

Both Sales and Purchase flows (orders and invoices) can override the Cash VAT configuration defined at the Organization and
Business Partner respectively by setting/unsetting the Cash VAT flag at the document header.

The C_GetTax function now accepts a new optional parameter to override the Cash VAT configuration defined at the Organization
or the Business Partner. This allows to properly purpose the right tax when entering order/invoice lines.


Created new tab Cash VAT under Sales/Purchase Invoice | Tax. It manages the tax amount that has been
paid for the invoice. It takes the percentage of the invoice that has been paid in a payment and it
calculates the correspondent tax amount and taxable amount for each tax included into the invoice.



Two new transitory tax accounts have been created to manage the Cash VAT. When an invoice is not yet paid/collected, the tax
amount is accounted to these transitory accounts. Once we pay/receive a payment, the correspondent amount is moved from the
transitory tax account to the final one. The Invoice, Payment, Transaction and Reconciliation accounting engines have been
modified to support the Cash VAT flows.

When an invoice has been paid from an order (prepayment), the accounting will use the final tax accounts instead of the transitory ones.

The COA importer now supports the new two transitory tax account defaults: T_CREDIT_TRANS_ACCT and T_DUE_TRANS_ACCT


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