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