src-db/database/model/functions/C_ORDER_POST1.xml
author RM packaging bot <staff.rm@openbravo.com>
Wed, 08 Aug 2018 05:44:35 +0000
changeset 34292 13cceb031649
parent 34285 5851f06c26be
child 34495 d535ae1bfc55
permissions -rw-r--r--
Merge temporary head for 3.0PR18Q3
carlos@0
     1
<?xml version="1.0"?>
adrian@94
     2
  <database name="FUNCTION C_ORDER_POST1">
adrian@94
     3
    <function name="C_ORDER_POST1" 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_order_id" type="VARCHAR" mode="in">
antonio@735
     8
        <default/>
antonio@735
     9
      </parameter>
miguel@23885
    10
      <parameter name="p_recalculatediscounts" type="VARCHAR" mode="in">
miguel@23885
    11
        <default><![CDATA[Y]]></default>
miguel@23885
    12
      </parameter>
gorkaion@239
    13
      <body><![CDATA[/*************************************************************************
carlos@0
    14
* The contents of this file are subject to the Openbravo  Public  License
priya@9085
    15
* Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
carlos@0
    16
* Version 1.1  with a permitted attribution clause; you may not  use this
carlos@0
    17
* file except in compliance with the License. You  may  obtain  a copy of
carlos@0
    18
* the License at http://www.openbravo.com/legal/license.html
carlos@0
    19
* Software distributed under the License  is  distributed  on  an "AS IS"
carlos@0
    20
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
carlos@0
    21
* License for the specific  language  governing  rights  and  limitations
carlos@0
    22
* under the License.
carlos@0
    23
* The Original Code is Openbravo ERP.
ggi@6702
    24
* The Initial Developer of the Original Code is Openbravo SLU
alvaro@33879
    25
* All portions are Copyright (C) 2001-2018 Openbravo SLU
carlos@0
    26
* All Rights Reserved.
carlos@0
    27
* Contributor(s):  ______________________________________.
carlos@0
    28
************************************************************************/
carlos@0
    29
  -- Logistics
carlos@0
    30
  v_ResultStr VARCHAR2(2000):='';
carlos@0
    31
  v_Message VARCHAR2(2000):='';
juanpablo@1605
    32
  v_Record_ID VARCHAR2(32);
juanpablo@1605
    33
  v_User VARCHAR2(32);
carlos@0
    34
  v_IsProcessing CHAR(1) ;
asier@2586
    35
  v_IsProcessed VARCHAR(60) ;
carlos@0
    36
  v_Result NUMBER:=1; -- Success
asier@1929
    37
  v_is_included NUMBER:=0;
asier@1929
    38
  v_is_ready AD_Org.IsReady%TYPE;
asier@1929
    39
  v_is_tr_allow AD_OrgType.IsTransactionsAllowed%TYPE;
carlos@0
    40
  -- Parameter
carlos@0
    41
  TYPE RECORD IS REF CURSOR;
carlos@0
    42
    Cur_Parameter RECORD;
pandeeswari@18818
    43
    Cur_line RECORD;
harikrishnan@5844
    44
    Cur_Order RECORD;
gorkaion@14380
    45
  -- Record Info
gorkaion@14380
    46
  v_Client_ID VARCHAR2(32);
gorkaion@14380
    47
  v_Org_ID VARCHAR2(32);
pandeeswari@21373
    48
  v_Warehouse_Org VARCHAR2(32);
gorkaion@14380
    49
  v_Org_Name VARCHAR2(60);
gorkaion@14380
    50
  v_UpdatedBy VARCHAR2(32);
gorkaion@14380
    51
  v_DocAction VARCHAR(60) ;
gorkaion@14380
    52
  v_DocStatus VARCHAR(60) ;
gorkaion@14380
    53
  v_InvoiceRule VARCHAR(60) ;
gorkaion@14380
    54
  v_M_Warehouse_ID VARCHAR2(32);
gorkaion@14380
    55
  v_DocType_ID VARCHAR2(32);
gorkaion@14380
    56
  v_DocTypeTarget_ID VARCHAR2(32);
gorkaion@14380
    57
  v_DocSubTypeSO VARCHAR(60) ;
gorkaion@14380
    58
  v_DocSubTypeSOTarget VARCHAR(60) ;
gorkaion@14546
    59
  v_IsReturnDocType CHAR(1);
gorkaion@14380
    60
  v_IsBinding CHAR(1):='Y';
gorkaion@17342
    61
  v_istaxincluded CHAR(1);
gorkaion@14380
    62
  --
victor@24222
    63
  ToDeliver NUMBER:=0;
victor@24222
    64
  ToInvoice NUMBER:=0;
victor@24222
    65
  ToDeliverOrToInvoice NUMBER:=0;
gorkaion@14380
    66
  --
gorkaion@14380
    67
  InOut_ID VARCHAR2(32);
gorkaion@14380
    68
  Invoice_ID VARCHAR2(32);
gorkaion@14380
    69
  --Added by P.SAROBE
gorkaion@14380
    70
  v_documentno_Settlement VARCHAR2(40);
gorkaion@14380
    71
  v_dateSettlement DATE;
gorkaion@14380
    72
  v_Cancel_Processed VARCHAR(60);
gorkaion@14380
    73
  v_nameBankstatement VARCHAR2 (60);
gorkaion@14380
    74
  v_dateBankstatement DATE;
gorkaion@14380
    75
  v_nameCash VARCHAR2 (60);
gorkaion@14380
    76
  v_dateCash DATE;
gorkaion@14380
    77
  v_Bankstatementline_ID VARCHAR2(32);
gorkaion@14380
    78
  --Finish added by P.Sarobe
gorkaion@14380
    79
  v_CashLine_ID VARCHAR2(32);
gorkaion@14380
    80
  v_ispaid CHAR(1);
gorkaion@14380
    81
  v_Settlement_Cancel_ID VARCHAR2(32);
gorkaion@14380
    82
  v_Cash_ID VARCHAR2(32):=NULL;
gorkaion@14380
    83
  v_Line NUMBER:=0;
gorkaion@14380
    84
  v_CashBook_ID VARCHAR2(32):=NULL;
gorkaion@14380
    85
  v_Debtpayment_ID VARCHAR2(32);
gorkaion@14380
    86
  v_ISO_Code VARCHAR(10) ;
gorkaion@14380
    87
  v_DocumentNo VARCHAR2(200) ;
gorkaion@14380
    88
  v_GrandTotal NUMBER;
gorkaion@14380
    89
  v_Date DATE;
gorkaion@14380
    90
  v_WarehouseName VARCHAR2(60) ;
gorkaion@14380
    91
  v_count NUMBER;
gorkaion@14380
    92
  v_isSoTrx CHAR(1) ;
gorkaion@14380
    93
  v_Aux NUMBER;
gorkaion@14380
    94
  v_c_Bpartner_ID VARCHAR2(32);
gorkaion@14380
    95
  v_c_currency_ID VARCHAR2(32);
gorkaion@14380
    96
  v_C_PROJECT_ID VARCHAR2(32);
gorkaion@14380
    97
  FINISH_PROCESS BOOLEAN:=FALSE;
gorkaion@14380
    98
  END_PROCESSING BOOLEAN:=FALSE;
gorkaion@14380
    99
  v_CBPartner_ID VARCHAR2(32);
gorkaion@14380
   100
  rowcount NUMBER;
unai@34024
   101
  v_stockqty NUMBER;
gorkaion@14380
   102
gorkaion@14380
   103
  v_CumDiscount NUMBER;
gorkaion@14380
   104
  v_OldCumDiscount NUMBER;
gorkaion@14380
   105
  v_OrderLineSeqNo NUMBER;
gorkaion@14380
   106
  Cur_COrderDiscount RECORD;
gorkaion@14380
   107
  Cur_TaxDiscount RECORD;
gorkaion@14380
   108
  v_OrderLine VARCHAR2(32);
gorkaion@14380
   109
  v_Discount NUMBER;
alvaro@31651
   110
  v_pricePrecision C_Currency.PricePrecision%TYPE;
alvaro@31651
   111
  v_stdPrecision C_Currency.StdPrecision%TYPE;
gorkaion@14380
   112
  Cur_OrderLine RECORD;
gorkaion@14380
   113
  v_DiscountExist NUMBER;
mikel@17452
   114
  v_gross_unit_price NUMBER;
mikel@17452
   115
  v_line_gross_amount NUMBER;
pandeeswari@18818
   116
  v_acctAmount NUMBER;
david@18488
   117
  v_reject_reason VARCHAR(32);
gorkaion@18749
   118
  v_dummy VARCHAR2(2000);
david@19194
   119
  v_bpartner_blocked VARCHAR2(1):='N';
david@19194
   120
  v_orderBlocking VARCHAR2(1):='N';
sandra@20002
   121
  v_bpartner_name c_bpartner.name%TYPE;
gorkaion@20944
   122
  v_productname m_product.name%TYPE;
david@19194
   123
victor@21535
   124
  v_iscashvat C_Order.IsCashVat%TYPE;
miguel@23885
   125
  v_recalculateDiscounts VARCHAR(1):='Y';
atul@24200
   126
  v_isactive VARCHAR2(1):='N';
victor@21535
   127
carlos@0
   128
  BEGIN
gorkaion@14380
   129
    IF (p_PInstance_ID IS NOT NULL) THEN
carlos@0
   130
      --  Update AD_PInstance
carlos@0
   131
      DBMS_OUTPUT.PUT_LINE('Updating PInstance - Processing ' || p_PInstance_ID) ;
carlos@0
   132
      v_ResultStr:='PInstanceNotFound';
antonio@735
   133
      AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'Y', NULL, NULL) ;
carlos@0
   134
      -- Get Parameters
carlos@0
   135
      v_ResultStr:='ReadingParameters';
carlos@0
   136
      FOR Cur_Parameter IN
gorkaion@14380
   137
        (SELECT i.Record_ID, i.AD_User_ID, p.ParameterName, p.P_String,
gorkaion@14380
   138
          p.P_Number, p.P_Date
carlos@0
   139
        FROM AD_PINSTANCE i
carlos@0
   140
        LEFT JOIN AD_PINSTANCE_PARA p
carlos@0
   141
          ON i.AD_PInstance_ID=p.AD_PInstance_ID
carlos@0
   142
        WHERE i.AD_PInstance_ID=p_PInstance_ID
carlos@0
   143
        ORDER BY p.SeqNo
carlos@0
   144
        )
carlos@0
   145
      LOOP
carlos@0
   146
        v_Record_ID:=Cur_Parameter.Record_ID;
carlos@0
   147
        v_User:=Cur_Parameter.AD_User_ID;
sanjota@29627
   148
        IF (Cur_Parameter.ParameterName = 'recalculateDiscounts') THEN
sanjota@29627
   149
          v_recalculateDiscounts := Cur_Parameter.P_String;
sanjota@29627
   150
        END IF;
carlos@0
   151
      END LOOP; -- Get Parameter
carlos@0
   152
    ELSE
carlos@0
   153
      v_Record_ID:=p_Order_ID;
miguel@23885
   154
      v_recalculateDiscounts := p_recalculateDiscounts;
carlos@0
   155
      SELECT CREATEDBY INTO v_User  FROM C_ORDER  WHERE C_ORDER_ID=p_Order_ID;
carlos@0
   156
    END IF;
carlos@0
   157
    DBMS_OUTPUT.PUT_LINE('  Record_ID=' || v_Record_ID) ;
carlos@0
   158
  BEGIN --BODY
alvaro@31651
   159
alvaro@31651
   160
  SELECT o.ISSOTRX, o.c_bpartner_id, o.DocAction, c.PricePrecision, c.StdPrecision, p.IsTaxIncluded
alvaro@31651
   161
  INTO v_IsSOTrx, v_c_Bpartner_ID, v_DocAction, v_pricePrecision, v_stdPrecision, v_isTaxIncluded
alvaro@31651
   162
  FROM C_ORDER o
alvaro@31651
   163
  JOIN C_CURRENCY c
alvaro@31651
   164
  ON o.C_CURRENCY_ID = c.C_CURRENCY_ID
alvaro@31651
   165
  JOIN M_PRICELIST p
alvaro@31651
   166
  ON o.M_PRICELIST_ID = p.M_PRICELIST_ID
alvaro@31651
   167
  WHERE o.C_ORDER_ID = v_Record_ID;
alvaro@31651
   168
pandeeswari@18818
   169
  /*Orderline acct dimension*/
pandeeswari@18818
   170
  IF (v_IsSOTrx = 'N') THEN
pandeeswari@18818
   171
    FOR Cur_line IN
pandeeswari@18818
   172
      (SELECT C_ORDERLINE.C_OrderLine_ID,
pandeeswari@18818
   173
       C_ORDERLINE.LinenetAmt
pandeeswari@18818
   174
       FROM C_ORDERLINE
pandeeswari@18818
   175
       WHERE C_Order_ID = v_Record_ID
pandeeswari@18818
   176
      )
pandeeswari@18818
   177
    LOOP
pandeeswari@18818
   178
      SELECT SUM(Amt) INTO v_acctAmount
pandeeswari@18818
   179
      FROM C_ORDERLINE_ACCTDIMENSION
pandeeswari@18818
   180
      WHERE C_OrderLine_ID = Cur_line.C_OrderLine_ID;
pandeeswari@18818
   181
      IF (v_acctAmount <> Cur_line.LinenetAmt) THEN
pandeeswari@18818
   182
        v_Message:='@QuantitiesNotMatch@';
pandeeswari@18818
   183
        RAISE_APPLICATION_ERROR(-20000, '@QuantitiesNotMatch@') ;
pandeeswari@18818
   184
      END IF;
pandeeswari@18818
   185
    END LOOP;
eduardo@28452
   186
  ELSE
eduardo@28452
   187
     IF (v_DocAction IN ('CO', 'PR')) THEN
alvaro@28892
   188
       SELECT COUNT(1) 
alvaro@28892
   189
         INTO v_Count
alvaro@28892
   190
       FROM DUAL 
alvaro@28892
   191
       WHERE EXISTS(SELECT 1
alvaro@28892
   192
		      FROM C_ORDERLINE, M_PRODUCT
alvaro@28892
   193
		      WHERE C_ORDERLINE.M_PRODUCT_ID = M_PRODUCT.M_PRODUCT_ID 
alvaro@28892
   194
		      AND ISLINKEDTOPRODUCT = 'Y'
alvaro@28892
   195
		      AND C_ORDER_ID = v_Record_ID
alvaro@28892
   196
		      AND NOT EXISTS (SELECT 1 FROM C_ORDERLINE_SERVICERELATION WHERE C_ORDERLINE_SERVICERELATION.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID));
alvaro@28892
   197
       IF (v_Count <> 0) THEN
eduardo@28452
   198
         v_Message:='@MissingServiceRelation@';
eduardo@28452
   199
         RAISE_APPLICATION_ERROR(-20000, '@MissingServiceRelation@') ;
eduardo@28452
   200
       END IF;
eduardo@28452
   201
     END IF;
pandeeswari@18818
   202
  END IF;
atul@24200
   203
atul@24200
   204
  /* Check active business partner*/
atul@24200
   205
  SELECT isactive INTO v_isactive
atul@24200
   206
  FROM C_Bpartner
atul@24200
   207
  WHERE C_Bpartner_ID = v_C_Bpartner_ID;
atul@24200
   208
atul@24200
   209
  IF(v_isactive = 'N') THEN
atul@24200
   210
    RAISE_APPLICATION_ERROR(-20000, '@InActiveBusinessPartner@');
atul@24200
   211
  END IF;
david@33278
   212
david@33278
   213
  --C_Order_Post - Validation_Process Extension Point
david@33278
   214
    SELECT count(*) INTO v_count
david@33278
   215
    FROM DUAL
david@33278
   216
    where exists (select 1 from ad_ep_procedures where ad_extension_points_id = '7D4A277CEBD74E57A68D8C53BB41C6DC');
david@33278
   217
    IF (v_count=1) THEN
david@33278
   218
      DECLARE
david@33278
   219
        v_ep_instance VARCHAR2(32);
david@33278
   220
        v_extension_point_id VARCHAR2(32) := '7D4A277CEBD74E57A68D8C53BB41C6DC';
david@33278
   221
      BEGIN
david@33278
   222
        v_ep_instance := get_uuid();
david@33278
   223
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Record_ID',
david@33278
   224
          v_record_id, NULL, NULL, NULL, NULL, NULL, NULL);
david@33278
   225
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'DocAction',
david@33278
   226
          v_DocAction, NULL, NULL, NULL, NULL, NULL, NULL);
david@33278
   227
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'User',
david@33278
   228
          v_User, NULL, NULL, NULL, NULL, NULL, NULL);
david@33278
   229
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Message',
david@33278
   230
          NULL, NULL, NULL, NULL, NULL, NULL, v_Message);
david@33278
   231
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Result',
david@33278
   232
          NULL, NULL, v_result, NULL, NULL, NULL, NULL);
david@33278
   233
        AD_EXTENSION_POINT_HANDLER(v_ep_instance, v_extension_point_id);
david@33278
   234
        SELECT p_number INTO v_Result
david@33278
   235
        FROM ad_ep_instance_para
david@33278
   236
        WHERE ad_ep_instance_id = v_ep_instance
david@33278
   237
          AND parametername LIKE 'Result';
david@33278
   238
        SELECT p_text INTO v_Message
david@33278
   239
        FROM ad_ep_instance_para
david@33278
   240
        WHERE ad_ep_instance_id = v_ep_instance
david@33278
   241
          AND parametername LIKE 'Message';
david@33278
   242
david@33278
   243
        DELETE FROM ad_ep_instance_para
david@33278
   244
        WHERE ad_ep_instance_id = v_ep_instance;
david@33278
   245
      END;
david@33278
   246
    END IF;
pandeeswari@18818
   247
  
carlos@0
   248
    /**
carlos@0
   249
    * Read Order
carlos@0
   250
    */
carlos@0
   251
    v_ResultStr:='ReadingOrder';
carlos@0
   252
    SELECT Processing, Processed, DocAction, DocStatus,
gorkaion@17342
   253
      C_DocType_ID, C_DocTypeTarget_ID, c_order.AD_Client_ID,
gorkaion@17342
   254
      c_order.AD_Org_ID, c_order.UpdatedBy, M_Warehouse_ID, TRUNC(DateOrdered),
gorkaion@17342
   255
      Issotrx, c_Bpartner_Id, c_order.c_currency_id, C_PROJECT_ID,
alvaro@31651
   256
      C_BPartner_ID, invoicerule, c_order.IsCashVat
gorkaion@14390
   257
    INTO v_IsProcessing, v_IsProcessed, v_DocAction, v_DocStatus,
asier@799
   258
      v_DocType_ID, v_DocTypeTarget_ID, v_Client_ID,
carlos@0
   259
      v_Org_ID, v_UpdatedBy, v_M_Warehouse_ID, v_Date,
carlos@379
   260
      v_isSoTrx, v_c_Bpartner_Id, v_c_currency_id, v_C_PROJECT_ID,
alvaro@31651
   261
      v_CBPartner_ID, v_invoicerule, v_iscashvat
sandra@25652
   262
    FROM C_ORDER
sandra@25652
   263
    WHERE C_Order_ID=v_Record_ID  FOR UPDATE  ;
sandra@25652
   264
    
carlos@0
   265
    -- Get current DocSubTypeSO
carlos@0
   266
    SELECT DocSubTypeSO
gorkaion@14546
   267
      INTO v_DocSubTypeSO
carlos@0
   268
    FROM C_DOCTYPE
carlos@0
   269
    WHERE C_DocType_ID=v_DocType_ID;
gorkaion@14546
   270
    SELECT DocSubTypeSO, isreturn
gorkaion@14546
   271
      INTO v_DocSubTypeSOTarget, v_isreturndoctype
gorkaion@14546
   272
    FROM C_DOCTYPE
gorkaion@14546
   273
    WHERE C_DocType_ID=v_DocTypetarget_ID;
david@19194
   274
atul@25237
   275
  IF(v_isreturndoctype='Y' AND v_DocAction='CO') THEN
atul@25237
   276
    DECLARE
atul@25237
   277
    v_RefReturnQty NUMBER:=0;
atul@25237
   278
    v_RefMovementQty NUMBER:=0;
atul@25237
   279
    BEGIN
atul@25237
   280
      v_Message:=NULL;
atul@25237
   281
      FOR Cur_line IN
atul@25237
   282
        (SELECT OL.M_INOUTLINE_ID, OL.LINE, OL.QTYORDERED
atul@25237
   283
        FROM C_ORDERLINE OL
atul@25237
   284
        WHERE OL.C_Order_ID = v_Record_ID
atul@25237
   285
        AND OL.M_INOUTLINE_ID IS NOT NULL
atul@25237
   286
        )
atul@25237
   287
      LOOP
atul@25237
   288
        SELECT COALESCE(SUM(OL.QtyOrdered),0) INTO v_RefReturnQty
atul@25237
   289
        FROM C_ORDERLINE OL, C_ORDER O
atul@25237
   290
        WHERE OL.M_INOUTLINE_ID = Cur_line.M_INOUTLINE_ID
atul@25237
   291
        AND OL.C_ORDER_ID = O.C_ORDER_ID
atul@25237
   292
        AND O.PROCESSED='Y';
atul@25237
   293
        SELECT MovementQty INTO v_RefMovementQty
atul@25237
   294
        FROM M_INOUTLINE WHERE M_INOUTLINE_ID = Cur_line.M_INOUTLINE_ID;
atul@25237
   295
        v_RefReturnQty:=ABS(v_RefReturnQty) + ABS(Cur_Line.QtyOrdered);
atul@25237
   296
        IF(v_RefReturnQty > v_RefMovementQty) THEN
atul@25237
   297
          IF(v_Message IS NULL) THEN
atul@25237
   298
            v_Message:=Cur_line.LINE;
atul@25237
   299
          ELSE
atul@25237
   300
            v_Message:=v_Message||', '||Cur_line.LINE;
atul@25237
   301
          END IF;
atul@25237
   302
        END IF;
atul@25237
   303
      END LOOP;
atul@25237
   304
      IF(v_Message IS NOT NULL) THEN
atul@25237
   305
        RAISE_APPLICATION_ERROR(-20000,'@ReturnQtyMismatch@'||v_Message);
atul@25237
   306
      END IF;
atul@25237
   307
    END;
atul@25237
   308
  END IF;
atul@25237
   309
pandeeswari@21353
   310
    --Check whether warehouse belongs to the organization.
pandeeswari@21353
   311
    SELECT count(AD_ORG_ID)
pandeeswari@21353
   312
    INTO v_count
pandeeswari@21353
   313
    FROM AD_Org_Warehouse
pandeeswari@21353
   314
    WHERE M_Warehouse_ID=v_M_Warehouse_ID
pandeeswari@21353
   315
    AND AD_Org_ID = v_Org_ID;
pandeeswari@21353
   316
pandeeswari@21335
   317
    IF v_count = 0 AND v_IsSOTrx = 'Y' THEN
pandeeswari@21353
   318
    RAISE_APPLICATION_ERROR(-20000,'@WrongWarehouse@') ;
pandeeswari@21353
   319
    END IF;
pandeeswari@21353
   320
pandeeswari@21373
   321
    SELECT AD_Org_ID
pandeeswari@21373
   322
    INTO v_Warehouse_Org
pandeeswari@21373
   323
    FROM M_Warehouse
pandeeswari@21373
   324
    WHERE M_Warehouse_ID = v_M_Warehouse_ID;
pandeeswari@21373
   325
pandeeswari@21373
   326
    IF(ad_org_isinnaturaltree(v_Warehouse_Org, v_Org_ID, v_Client_ID) = 'N' AND v_isSoTrx = 'N') THEN
pandeeswari@21373
   327
      RAISE_APPLICATION_ERROR(-20000,'@WrongWarehouse@');
pandeeswari@21373
   328
    END IF;
pandeeswari@21373
   329
david@19194
   330
    SELECT CASE WHEN (m.ISSOTRX='Y') THEN customer_blocking  ELSE vendor_blocking END ,  
david@19194
   331
    CASE WHEN (m.ISSOTRX='Y') THEN so_order_blocking ELSE po_order_blocking  END, name, DocAction
david@19194
   332
      INTO v_bpartner_blocked, v_orderBlocking, v_bpartner_name, v_DocAction
david@19194
   333
    FROM C_ORDER m, C_BPartner bp
david@19194
   334
    WHERE m.c_bpartner_id=bp.c_bpartner_id
david@19194
   335
    AND m.C_ORDER_ID=v_Record_ID
david@19194
   336
    AND m.C_BPARTNER_ID=v_c_Bpartner_ID;
david@19194
   337
    IF (v_DocAction = 'CO' AND v_bpartner_blocked = 'Y' AND v_orderBlocking = 'Y' AND v_isreturndoctype='N' ) THEN
david@19194
   338
      RAISE_APPLICATION_ERROR(-20000,'@ThebusinessPartner@'||' '|| v_bpartner_name ||' '||'@BusinessPartnerBlocked@');
david@19194
   339
    END IF;
gorkaion@14380
   340
    -- Get the name of the org of the Order. Added by P.Sarobe
gorkaion@14380
   341
    SELECT name INTO v_Org_Name FROM AD_ORG WHERE ad_org_id = v_Org_ID;
asier@799
   342
    DBMS_OUTPUT.PUT_LINE('DocAction=' || v_DocAction || ', DocStatus=' || v_DocStatus || ', DocType_ID=' || v_DocType_ID || ', DocTypeTarget_ID=' || v_DocTypeTarget_ID || ', DocSubTypeSO=' || v_DocSubTypeSO) ;
gorkaion@14380
   343
gorkaion@20976
   344
    SELECT count(*) INTO v_count
gorkaion@20976
   345
    FROM dual
gorkaion@20976
   346
    WHERE EXISTS (
gorkaion@20976
   347
        SELECT 1
gorkaion@20976
   348
        FROM c_orderline ol JOIN m_product p ON ol.m_product_id = p.m_product_id
gorkaion@20976
   349
        WHERE ol.c_order_id = v_record_id
gorkaion@20976
   350
          AND p.isgeneric = 'Y');
gorkaion@20976
   351
    IF (v_count > 0) THEN
gorkaion@20976
   352
      SELECT max(p.name) INTO v_productname
gorkaion@20976
   353
      FROM c_orderline ol JOIN m_product p ON ol.m_product_id = p.m_product_id
gorkaion@20976
   354
      WHERE ol.c_order_id = v_record_id
gorkaion@20976
   355
        AND p.isgeneric = 'Y';
gorkaion@20944
   356
      RAISE_APPLICATION_ERROR(-20000, '@CannotUseGenericProduct@ ' || v_productName);
gorkaion@20944
   357
    END IF;
gorkaion@20944
   358
alvaro@34067
   359
    /*PLM Status*/
alvaro@34067
   360
    IF (v_DocAction = 'CO' AND v_IsSOTrx = 'Y' AND v_isreturndoctype = 'N') THEN
asier@34044
   361
      FOR Cur_line IN
alvaro@34067
   362
        (SELECT SUM(ol.qtyordered) AS qtyordered, ol.m_product_id, ol.c_uom_id, p.name, ps.restrictsalefrombackend, ps.restrictsaleoutofstock
asier@34044
   363
         FROM c_orderline ol
asier@34044
   364
         JOIN m_product p ON ol.m_product_id = p.m_product_id
asier@34044
   365
         JOIN m_product_status ps ON p.m_product_status_id = ps.m_product_status_id
asier@34044
   366
         WHERE ol.c_order_id = v_Record_ID
asier@34044
   367
         AND (ps.restrictsalefrombackend = 'Y' OR ps.restrictsaleoutofstock = 'Y')
alvaro@34067
   368
         GROUP BY ol.m_product_id, ol.c_uom_id, p.name, ps.restrictsalefrombackend, ps.restrictsaleoutofstock)
asier@34044
   369
      LOOP
asier@34044
   370
        IF (Cur_line.restrictsalefrombackend = 'Y') THEN
asier@34044
   371
          RAISE_APPLICATION_ERROR(-20000, '@CannotUseLockedProduct@ ' || Cur_line.name || '. @VerifyPLMStatus@.');
asier@34044
   372
        ELSIF (Cur_line.restrictsaleoutofstock = 'Y') THEN
alvaro@34067
   373
          SELECT COALESCE(SUM(sd.qtyonhand - sd.reservedqty), 0) INTO v_stockqty
asier@34044
   374
          FROM m_storage_detail sd
asier@34044
   375
          JOIN m_locator loc on loc.m_locator_id = sd.m_locator_id
asier@34044
   376
          WHERE sd.m_product_id = Cur_line.m_product_id
asier@34044
   377
          AND sd.c_uom_id = Cur_line.c_uom_id
asier@34044
   378
          AND EXISTS (SELECT 1
asier@34044
   379
                      FROM AD_Org_Warehouse w
asier@34044
   380
                      WHERE w.ad_org_id = v_Org_ID
asier@34044
   381
                      AND w.m_warehouse_id = loc.m_warehouse_id);
unai@34024
   382
asier@34044
   383
          IF (Cur_line.qtyordered > v_stockqty) THEN
asier@34055
   384
            RAISE_APPLICATION_ERROR(-20000, '@CannotUseDiscontinuedProduct@ ' || Cur_line.name || '. @ProductDiscontinuedNoStock@ (' || v_stockqty || '). @VerifyPLMStatus@.');
asier@34044
   385
          END IF;
asier@34044
   386
        END IF;
asier@34044
   387
      END LOOP;
unai@34024
   388
    END IF;
unai@34024
   389
gorkaion@18752
   390
    /** 
gorkaion@18752
   391
    * Quotations
gorkaion@18752
   392
    */
gorkaion@18752
   393
    IF (v_DocSubTypeSOTarget = 'OB'AND v_DocAction = 'RJ') THEN
gorkaion@18752
   394
      SELECT c_reject_reason_id
gorkaion@18752
   395
        INTO v_reject_reason
gorkaion@18752
   396
      FROM C_ORDER
gorkaion@18752
   397
      WHERE C_Order_ID=v_Record_ID;
gorkaion@18752
   398
      IF (v_reject_reason IS NULL) THEN
gorkaion@18752
   399
        RAISE_APPLICATION_ERROR(-20000, '@NoRejectReason@') ;
gorkaion@18752
   400
      END IF;
david@20461
   401
      /*
david@20461
   402
        * Undo inventory reservation
david@20461
   403
        */
david@20461
   404
        BEGIN
david@20461
   405
          v_ResultStr:='ReserveInventory';
david@20461
   406
          -- Set reserved quantity to 0
david@20461
   407
          UPDATE C_ORDERLINE
david@20461
   408
          SET QtyReserved = 0,
david@20461
   409
              Updated=now(),
david@20461
   410
              UpdatedBy=v_User
david@20461
   411
          WHERE c_orderline_id IN (select c_orderline_id
david@20461
   412
                                   from c_orderline
david@20461
   413
                                   where c_order_id = v_Record_id);
david@20461
   414
        END;
gorkaion@18752
   415
      UPDATE C_ORDER
gorkaion@18752
   416
      SET DocStatus='CJ',
gorkaion@18752
   417
          DocAction='--',
gorkaion@18752
   418
          Processed='Y',
gorkaion@18752
   419
          Updated=now(),
gorkaion@18752
   420
          UpdatedBy=v_User
gorkaion@18752
   421
      WHERE C_Order_ID=v_Record_ID;
gorkaion@18752
   422
      IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@18752
   423
      	--  Update AD_PInstance
gorkaion@18752
   424
      	DBMS_OUTPUT.PUT_LINE('Updating PInstance - Finished - ' || v_Message) ;
gorkaion@18752
   425
        AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'N', v_Result, v_Message) ;
gorkaion@18752
   426
      END IF;
gorkaion@18752
   427
      RETURN;
gorkaion@18752
   428
    END IF;
gorkaion@18752
   429
gorka@1069
   430
    /**
gorka@1069
   431
    * Check if order has lines
gorka@1069
   432
    */
pandeeswari@22034
   433
    IF (v_DocAction = 'CO' OR v_DocAction = 'PR') THEN
gorka@1069
   434
      SELECT COUNT(*)
alvaro@28892
   435
      INTO v_Aux
alvaro@28892
   436
      FROM C_ORDERLINE
alvaro@28892
   437
      WHERE C_ORDER_ID = v_Record_ID;
alvaro@28892
   438
      IF (v_Aux = 0) THEN
alvaro@28892
   439
        RAISE_APPLICATION_ERROR(-20000, '@OrderWithoutLines@');
alvaro@28892
   440
      END IF;
alvaro@28892
   441
    END IF;
alvaro@28892
   442
alvaro@28892
   443
    /**
alvaro@28892
   444
    * Check if already processed / reactivated
alvaro@28892
   445
    */
alvaro@28892
   446
    IF (v_DocAction = 'CO' OR v_DocAction = 'PR') THEN
alvaro@28892
   447
      IF (v_IsProcessed = 'Y') THEN
alvaro@28892
   448
        RAISE_APPLICATION_ERROR(-20000,'@AlreadyPosted@');
alvaro@28892
   449
      END IF;
alvaro@28892
   450
    ELSIF (v_DocAction='RE') THEN
alvaro@28892
   451
      IF (v_IsProcessed = 'N') THEN
alvaro@28892
   452
        RAISE_APPLICATION_ERROR(-20000,'@ActionNotSupported@');
alvaro@28892
   453
      END IF;
gorka@1069
   454
    END IF;
gorkaion@14380
   455
victor@21535
   456
    -- Check the cash vat flag for all the taxes matches the order one
victor@21535
   457
    IF (v_DocAction IN ('CO', 'PR')) THEN
victor@21535
   458
      select count(1)
victor@21535
   459
      into v_Aux
victor@21535
   460
      from c_ordertax ot inner join c_tax t on (ot.c_tax_id = t.c_tax_id)
victor@21535
   461
      where ot.c_order_id = v_Record_ID
victor@21909
   462
      and t.iswithholdingtax = 'N'
victor@21909
   463
      and t.rate <> 0
victor@21535
   464
      and t.IsCashVat <> v_iscashvat;
victor@21535
   465
victor@21535
   466
      IF (v_Aux > 0) THEN
victor@21535
   467
        RAISE_APPLICATION_ERROR(-20000, '@CashVATNotMatch@');
victor@21535
   468
      END IF;
victor@21535
   469
    END IF;
victor@21535
   470
carlos@0
   471
    /**
carlos@0
   472
    * Order Closed, Voided or Reversed - No action possible
carlos@0
   473
    */
carlos@0
   474
    IF(v_DocStatus IN('CL', 'VO', 'RE')) THEN
carlos@0
   475
      RAISE_APPLICATION_ERROR(-20000, '@AlreadyPosted@') ;
carlos@0
   476
    END IF;
gorkaion@14380
   477
gorkaion@14380
   478
    /**
gorkaion@14380
   479
    * Waiting on Prepayment  can only be closed
gorkaion@14380
   480
    */
gorkaion@14380
   481
    IF(v_DocStatus='WP' AND v_DocAction<>'CL') THEN
gorkaion@14380
   482
      RAISE_APPLICATION_ERROR(-20000, '@WaitingPayment@') ;
gorkaion@14380
   483
    END IF;
gorkaion@14380
   484
ainhoa@3126
   485
    IF (v_DocSubTypeSOTarget='PR' AND v_invoicerule <> 'I') THEN
carlos@0
   486
      RAISE_APPLICATION_ERROR(-20000, '@PrepayMustImmediate@');
carlos@0
   487
    END IF;
gorkaion@14380
   488
    /**
gorkaion@14380
   489
    * Unlock
gorkaion@14380
   490
    */
gorkaion@14380
   491
    IF(v_DocAction='XL') THEN
gorkaion@14380
   492
      UPDATE C_ORDER
gorkaion@14380
   493
        SET Processing='N',
gorkaion@14380
   494
        DocAction='--',
gorkaion@14380
   495
        Updated=now(),
gorkaion@14380
   496
        UpdatedBy=v_User
gorkaion@14380
   497
      WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
   498
      FINISH_PROCESS:=TRUE;
gorkaion@14380
   499
    END IF;
carlos@0
   500
    IF(NOT FINISH_PROCESS) THEN
carlos@0
   501
      IF(v_IsProcessing='Y') THEN
carlos@0
   502
        RAISE_APPLICATION_ERROR(-20000, '@OtherProcessActive@') ;
carlos@0
   503
      END IF;
gorkaion@14380
   504
carlos@0
   505
      /**
carlos@0
   506
      * Re-activate
carlos@0
   507
      */
gorkaion@14380
   508
      IF (v_DocAction='RE') THEN
gorkaion@14390
   509
        IF (v_DocSubTypeSO IN ('WR', 'WI')) THEN
gorkaion@3775
   510
          RAISE_APPLICATION_ERROR(-20000, '@ActionNotSupported@');
gorkaion@3775
   511
        END IF;
carlos@0
   512
        --Verify not managed debtPayments added by ALO
gorkaion@14380
   513
        --Added by P.Sarobe. New messages
carlos@0
   514
        SELECT max(c_debt_payment_id), COUNT(*)
gorkaion@14380
   515
          INTO v_Debtpayment_ID, v_Aux
carlos@0
   516
        FROM C_DEBT_PAYMENT
carlos@0
   517
        WHERE C_Order_ID=v_Record_ID
carlos@0
   518
          AND C_Debt_Payment_Status(C_Settlement_Cancel_ID, Cancel_Processed, Generate_Processed, IsPaid, IsValid, C_CashLine_ID, C_BankStatementLine_ID)!='P';
gorkaion@14380
   519
        IF (v_Aux != 0) THEN
gorkaion@14380
   520
          --Added by P.Sarobe. New messages
gorkaion@14380
   521
          SELECT c_Bankstatementline_Id, c_cashline_id, c_settlement_cancel_id, ispaid, cancel_processed
gorkaion@14380
   522
            INTO v_Bankstatementline_ID, v_CashLine_ID, v_Settlement_Cancel_ID, v_ispaid, v_Cancel_Processed
gorkaion@14380
   523
          FROM C_DEBT_PAYMENT WHERE C_Debt_Payment_ID = v_Debtpayment_ID;
gorkaion@14380
   524
gorkaion@14380
   525
          IF (v_Bankstatementline_ID IS NOT NULL) THEN
gorkaion@14380
   526
            SELECT C_BANKSTATEMENT.NAME, C_BANKSTATEMENT.STATEMENTDATE
gorkaion@14380
   527
              INTO v_nameBankstatement, v_dateBankstatement
gorkaion@14380
   528
            FROM C_BANKSTATEMENT, C_BANKSTATEMENTLINE
gorkaion@14380
   529
            WHERE C_BANKSTATEMENT.C_BANKSTATEMENT_ID = C_BANKSTATEMENTLINE.C_BANKSTATEMENT_ID
gorkaion@14380
   530
              AND C_BANKSTATEMENTLINE.C_BANKSTATEMENTLINE_ID = v_Bankstatementline_ID;
gorkaion@14380
   531
            RAISE_APPLICATION_ERROR(-20000, '@ManagedDebtPaymentOrderBank@'||v_nameBankstatement||' '||'@Bydate@'||v_dateBankstatement) ;
gorkaion@14380
   532
          END IF;
gorkaion@14380
   533
          IF (v_CashLine_ID IS NOT NULL) THEN
gorkaion@14380
   534
            SELECT C_CASH.NAME, C_CASH.STATEMENTDATE
gorkaion@14380
   535
              INTO v_nameCash, v_dateCash
gorkaion@14380
   536
            FROM C_CASH, C_CASHLINE
gorkaion@14380
   537
            WHERE C_CASH.C_CASH_ID = C_CASHLINE.C_CASH_ID
gorkaion@14380
   538
              AND C_CASHLINE.C_CASHLINE_ID = v_CashLine_ID;
gorkaion@14380
   539
            RAISE_APPLICATION_ERROR(-20000, '@ManagedDebtPaymentOrderCash@'||v_nameCash||' '||'@Bydate@'||v_dateCash) ;
gorkaion@14380
   540
          END IF;
gorkaion@14380
   541
          IF (v_Cancel_Processed='Y' AND v_ispaid='N') THEN
gorkaion@14380
   542
            SELECT documentno, datetrx
gorkaion@14380
   543
              INTO v_documentno_Settlement, v_dateSettlement
gorkaion@14380
   544
            FROM C_SETTLEMENT
gorkaion@14380
   545
            WHERE C_SETTLEMENT_ID = v_Settlement_Cancel_ID;
gorkaion@14380
   546
            RAISE_APPLICATION_ERROR(-20000, '@ManagedDebtPaymentOrderCancel@'||v_documentno_Settlement||' '||'@Bydate@'||v_dateSettlement) ;
gorkaion@14380
   547
          END IF;
carlos@0
   548
        END IF;
gorkaion@14380
   549
gorkaion@14380
   550
        DBMS_OUTPUT.PUT_LINE('Re-Activating ' || v_DocSubTypeSO || ': ' || v_Record_ID) ;
gorkaion@14380
   551
        IF(v_DocSubTypeSO IN ('WI', 'WP', 'WR')) THEN
gorkaion@14380
   552
          -- Cancel existing Deli very + Invoice Documents
gorkaion@14380
   553
          M_INOUT_CANCEL(NULL, v_Record_ID) ;
gorkaion@14380
   554
          IF (v_DocSubTypeSO<>'WP') THEN
gorkaion@14380
   555
            C_INVOICE_CANCEL(NULL, v_Record_ID);
carlos@0
   556
          END IF;
gorkaion@14380
   557
        END IF;
gorkaion@14380
   558
        -- Update Order
gorkaion@14380
   559
        v_ResultStr:='ReActivate';
gorkaion@14380
   560
        UPDATE C_ORDER
gorkaion@14380
   561
        SET DocStatus='IP', -- In Progress
gorkaion@14390
   562
            DocAction='CO',
carlos@0
   563
            Processing='N',
carlos@0
   564
            Processed='N',
harikrishnan@7253
   565
            Updated=now(),
harikrishnan@7253
   566
            UpdatedBy=v_User
gorkaion@14380
   567
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
   568
        UPDATE M_INOUTLINE SET C_ORDERLINE_ID = NULL
gorkaion@14380
   569
        WHERE (SELECT DISTINCT A.DOCSTATUS FROM M_INOUT A, M_INOUTLINE B, C_ORDERLINE C
gorkaion@14380
   570
               WHERE A.M_INOUT_ID = B.M_INOUT_ID AND B.C_ORDERLINE_ID = C.C_ORDERLINE_ID
gorkaion@14380
   571
                 AND C.C_ORDER_DISCOUNT_ID IS NOT NULL AND C.C_ORDER_ID = v_Record_ID) = 'VO'
gorkaion@14380
   572
                 AND C_ORDERLINE_ID IN (SELECT C_ORDERLINE_ID FROM C_ORDERLINE WHERE C_ORDER_DISCOUNT_ID IS NOT NULL 
gorkaion@14380
   573
                 AND C_ORDER_ID = v_Record_ID);
atul@31807
   574
	DELETE
atul@31807
   575
	FROM C_ORDERLINETAX
atul@31807
   576
	WHERE EXISTS (SELECT 1
atul@31807
   577
                     FROM C_ORDERLINE
atul@31807
   578
                     WHERE C_ORDER_DISCOUNT_ID IS NOT NULL
atul@31807
   579
		      AND C_ORDER_ID = v_Record_ID
atul@31807
   580
		      AND C_ORDERLINE.C_ORDERLINE_ID = C_ORDERLINETAX.C_ORDERLINE_ID);
gorkaion@14380
   581
        DELETE
gorkaion@14380
   582
        FROM C_ORDERLINE
gorkaion@14380
   583
        WHERE C_ORDER_DISCOUNT_ID IS NOT NULL
victor@3675
   584
          AND C_ORDER_ID=v_Record_ID;
gorkaion@14380
   585
        --ADDED BY E.ARGAL
gorkaion@14380
   586
        --Invalidate debt payments added by ALO
gorkaion@14380
   587
        UPDATE C_DEBT_PAYMENT
gorkaion@14380
   588
        SET IsValid='N',
harikrishnan@7253
   589
            Updated=now(),
harikrishnan@7253
   590
            UpdatedBy=v_User
gorkaion@14380
   591
        WHERE C_Order_ID=v_Record_ID
gorkaion@14380
   592
          AND IsAutomaticGenerated='N';
carlos@0
   593
gorkaion@14380
   594
        DELETE
gorkaion@14380
   595
        FROM C_CASHLINE
gorkaion@14380
   596
        WHERE C_Debt_Payment_Id IN
carlos@0
   597
            (SELECT C_DEBT_PAYMENT_ID
carlos@0
   598
            FROM C_DEBT_PAYMENT
carlos@0
   599
            WHERE C_Order_ID=v_Record_ID
carlos@0
   600
              AND COALESCE(IsAutomaticGenerated, 'Y')='Y'
gorkaion@14380
   601
            );
gorkaion@14380
   602
        DELETE
gorkaion@14380
   603
        FROM C_DEBT_PAYMENT
gorkaion@14380
   604
        WHERE C_Order_ID=v_Record_ID
gorkaion@14380
   605
          AND COALESCE(IsAutomaticGenerated, 'Y')='Y';
gorkaion@14380
   606
        /*
gorkaion@14380
   607
        * Undo inventory reservation
gorkaion@14380
   608
        */
gorkaion@14380
   609
        DECLARE
gorkaion@14380
   610
          Cur_ResLine RECORD;
gorkaion@14380
   611
          v_QtySO NUMBER; -- Reserved
gorkaion@14380
   612
          v_QtyOrderSO NUMBER;
gorkaion@14380
   613
          v_QtyPO NUMBER; -- Ordered
gorkaion@14380
   614
          v_QtyOrderPO NUMBER;
alvaro@29579
   615
          v_UOM_ID VARCHAR2(32);
gorkaion@14380
   616
        BEGIN
gorkaion@14380
   617
          v_ResultStr:='ReserveInventory';
gorkaion@14380
   618
          -- For all lines needing reservation
gorkaion@14380
   619
          FOR Cur_ResLine IN
gorkaion@14380
   620
            (SELECT l.M_Warehouse_ID, l.M_Product_ID, l.M_AttributeSetInstance_ID, l.C_OrderLine_ID,
gorkaion@14380
   621
                 l.QtyOrdered AS Qty, l.QUANTITYORDER, l.qtyreserved, l.qtydelivered,
markmm82@30851
   622
                l.C_UOM_ID, l.M_PRODUCT_UOM_ID, l.C_AUM
gorkaion@14380
   623
             FROM C_ORDERLINE l, M_PRODUCT p
gorkaion@14380
   624
             WHERE l.C_Order_ID=v_Record_ID  -- Reserve Products (not: services, null products)
gorkaion@14380
   625
               AND l.M_Product_ID=p.M_Product_ID
gorkaion@14380
   626
               AND p.IsStocked='Y'
sandra@25652
   627
               AND p.ProductType='I' 
gorkaion@14380
   628
             )
carlos@0
   629
            LOOP
gorkaion@14380
   630
            -- Qty corrected for SO/PO
gorkaion@14390
   631
            IF (v_DocSubTypeSO IS NULL) THEN
gorkaion@14380
   632
              v_QtySO:=0;
gorkaion@14380
   633
              v_QtyOrderSO:=NULL;
gorkaion@14380
   634
              v_QtyPO:=Cur_ResLine.qtydelivered-Cur_ResLine.qty;
gorkaion@14380
   635
              v_QtyOrderPO:=NULL;
gorkaion@14380
   636
              IF (Cur_ResLine.QtyDelivered=0) THEN
gorkaion@14380
   637
                v_QtyOrderPO := -Cur_ResLine.QuantityOrder;
david@30807
   638
              ELSIF Cur_ResLine.C_AUM IS NULL AND Cur_ResLine.M_Product_UOM_ID IS NOT NULL THEN
alvaro@29579
   639
                SELECT c_uom_id
alvaro@29579
   640
                INTO v_UOM_ID
alvaro@29579
   641
                FROM m_product_uom
alvaro@29579
   642
                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
alvaro@29579
   643
                v_QtyOrderPO := -C_Uom_Convert(v_QtyPO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
carlos@0
   644
              END IF;
gorkaion@14380
   645
            ELSE
gorkaion@14380
   646
              v_QtySO:=-Cur_ResLine.QtyReserved;
gorkaion@14380
   647
              IF (Cur_ResLine.QtyReserved=Cur_ResLine.Qty) THEN
gorkaion@14380
   648
                v_QtyOrderSO := -Cur_ResLine.QuantityOrder;
david@30807
   649
              ELSIF Cur_ResLine.C_AUM IS NULL AND Cur_ResLine.M_Product_UOM_ID IS NOT NULL THEN
alvaro@29579
   650
                SELECT c_uom_id
alvaro@29579
   651
                INTO v_UOM_ID
alvaro@29579
   652
                FROM m_product_uom
alvaro@29579
   653
                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
alvaro@29579
   654
                v_QtyOrderSO := -C_Uom_Convert(v_QtySO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
harikrishnan@7910
   655
              END IF;
gorkaion@14380
   656
              v_QtyPO:=0;
gorkaion@14380
   657
              v_QtyOrderPO:=NULL;
gorkaion@14380
   658
            END IF;
jon@21226
   659
            IF ((v_DocStatus<>'IP' OR v_DocAction<>'CO') AND COALESCE(v_DocSubTypeSO, '')<>'OB') THEN
gorkaion@14380
   660
              M_UPDATE_STORAGE_PENDING(v_Client_ID, v_Org_ID, v_UpdatedBy, Cur_ResLine.M_Product_ID, Cur_ResLine.M_Warehouse_ID, Cur_ResLine.M_AttributeSetInstance_ID, Cur_ResLine.C_UOM_ID, Cur_ResLine.M_PRODUCT_UOM_ID, v_QtySO, v_QtyOrderSO, v_QtyPO, v_QtyOrderPO) ;
gorkaion@14380
   661
            END IF;
gorkaion@14380
   662
          END LOOP;
gorkaion@2658
   663
          -- Set reserved quantity to 0
gorkaion@2658
   664
          UPDATE C_ORDERLINE
harikrishnan@7253
   665
          SET QtyReserved = 0,
gorkaion@14380
   666
              Updated=now(),
gorkaion@14380
   667
              UpdatedBy=v_User
gorkaion@2658
   668
          WHERE c_orderline_id IN (select c_orderline_id
gorkaion@2658
   669
                                   from c_orderline
gorkaion@2658
   670
                                   where c_order_id = v_Record_id);
mikel@17452
   671
        END;
gorkaion@18717
   672
        /**
gorkaion@18717
   673
        *  Manage Stock Reservations
gorkaion@18717
   674
        */
gorkaion@18749
   675
        SELECT COUNT(1) INTO v_count
gorkaion@18749
   676
        FROM ad_preference
gorkaion@18749
   677
        WHERE property = 'StockReservations';
gorkaion@18749
   678
        IF (v_count > 1) THEN
david@34188
   679
          v_dummy := AD_GET_PREFERENCE_VALUE('StockReservations', 'Y', v_client_id, v_org_id, v_User, NULL, NULL);
alvaro@33879
   680
          DBMS_OUTPUT.PUT_LINE('StockReservations preference value: ' || v_dummy);
gorkaion@18749
   681
        ELSIF (v_count = 1) THEN
gorkaion@18749
   682
          UPDATE c_orderline
gorkaion@18749
   683
          SET so_res_status = NULL
gorkaion@18749
   684
          WHERE c_order_id = v_Record_id;
gorkaion@18749
   685
          UPDATE c_order
gorkaion@18749
   686
          SET so_res_status = NULL
gorkaion@18749
   687
          WHERE c_order_id = v_record_id;
gorkaion@18749
   688
        END IF;
gorkaion@2658
   689
gorkaion@14380
   690
        --ADDED BY P.SAROBE but to be deprecated 26052007
gorkaion@14380
   691
        SELECT MAX(C_CASHLINE_ID)
carlos@0
   692
          INTO v_CashLine_ID
gorkaion@14380
   693
        FROM C_CASHLINE
gorkaion@14380
   694
        WHERE C_ORDER_ID=v_Record_ID;
gorkaion@14380
   695
        IF (v_CashLine_ID IS NOT NULL) THEN
gorkaion@14380
   696
          SELECT PROCESSED
carlos@0
   697
            INTO v_IsProcessed
gorkaion@14380
   698
          FROM C_CASH, C_CASHLINE
gorkaion@14380
   699
          WHERE C_CASH.C_CASH_ID=C_CASHLINE.C_CASH_ID
gorkaion@14380
   700
            AND C_CASHLINE_ID=v_CashLine_ID;
gorkaion@14380
   701
          IF (v_IsProcessed='N') THEN
gorkaion@14380
   702
            DELETE FROM C_CASHLINE WHERE C_CASHLINE_ID=v_CashLine_ID;
gorkaion@14380
   703
          ELSE
gorkaion@14380
   704
            SELECT C_CASH.NAME, C_CASH.STATEMENTDATE, C_CASHLINE.LINE
gorkaion@14380
   705
              INTO v_nameCash, v_dateCash, v_Line
gorkaion@14380
   706
            FROM C_CASH, C_CASHLINE
gorkaion@14380
   707
            WHERE C_CASH.C_CASH_ID = C_CASHLINE.C_CASH_ID
gorkaion@14380
   708
              AND C_CASHLINE.C_CASHLINE_ID = v_CashLine_ID;
gorkaion@14380
   709
            RAISE_APPLICATION_ERROR(-20000, '@Ordercahslineprocessed@'||v_nameCash||' '||'@Bydate@'||v_dateCash||' '||'@line@'||v_Line) ;
gorkaion@14380
   710
          END IF;
carlos@0
   711
        END IF;
carlos@0
   712
carlos@0
   713
        UPDATE C_ORDER
gorkaion@14380
   714
        SET DocStatus='DR', -- Draft
gorkaion@14390
   715
            DocAction='CO',
carlos@0
   716
            Processing='N',
harikrishnan@7253
   717
            Updated=now(),
harikrishnan@7253
   718
            UpdatedBy=v_User
gorkaion@14380
   719
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
   720
carlos@0
   721
        FINISH_PROCESS:=TRUE;
carlos@0
   722
      END IF;
carlos@0
   723
    END IF;--FINISH_PROCESS
gorkaion@14380
   724
    IF (NOT FINISH_PROCESS) THEN
gorkaion@14380
   725
      SELECT COUNT(*)
gorkaion@14380
   726
        INTO v_Count
gorkaion@14380
   727
      FROM C_ORDER C, C_DOCTYPE
gorkaion@14390
   728
      WHERE C_DocType.DocBaseType IN ('SOO', 'POO')
gorkaion@14380
   729
        AND C_DocType.IsSOTrx=C.ISSOTRX
gorkaion@14380
   730
        AND AD_ISORGINCLUDED(C.AD_Org_ID,C_DocType.AD_Org_ID, C.AD_Client_ID) <> -1
gorkaion@14380
   731
        AND C.C_DOCTYPETARGET_ID = C_DOCTYPE.C_DOCTYPE_ID
gorkaion@14380
   732
        AND C.C_ORDER_ID = v_Record_ID;
gorkaion@14380
   733
      IF (v_Count=0) THEN
gorkaion@14380
   734
        RAISE_APPLICATION_ERROR(-20000, '@NotCorrectOrgDoctypeOrder@') ;
carlos@0
   735
      END IF;
carlos@0
   736
pandeeswari@18808
   737
      SELECT COUNT(*)
pandeeswari@18808
   738
        INTO v_Count
pandeeswari@18808
   739
      FROM C_ORDER C, C_ORDERLINE OL
pandeeswari@18808
   740
      WHERE C.C_ORDER_ID = OL.C_ORDER_ID
eduardo@19387
   741
        AND AD_ISORGINCLUDED(OL.AD_Org_ID, C.AD_Org_ID, C.AD_Client_ID) = -1
pandeeswari@18808
   742
        AND C.C_ORDER_ID = v_Record_ID;
eduardo@19387
   743
      IF (v_Count>0) THEN
pandeeswari@18808
   744
        RAISE_APPLICATION_ERROR(-20000, '@NotCorrectOrgLines@') ;
pandeeswari@18808
   745
      END IF;
pandeeswari@18808
   746
      
carlos@0
   747
carlos@0
   748
      /**
carlos@0
   749
      * Close Order - prepare
carlos@0
   750
      */
ioritz@18421
   751
      DECLARE
ioritz@18421
   752
          Cur_Inventory RECORD;
ioritz@18421
   753
          v_QtyOrdered NUMBER;
atul@31807
   754
          v_QtyAum NUMBER;
ioritz@18421
   755
          v_QuantityOrder NUMBER;
ioritz@18421
   756
          v_linenetamt NUMBER;
ioritz@18588
   757
          v_linegrossamt NUMBER;
ioritz@18421
   758
          v_ProductUOM M_PRODUCT_UOM.C_UOM_ID%TYPE;
ioritz@18421
   759
      BEGIN
ioritz@18421
   760
ioritz@18421
   761
        -- When closing the order it calculates the difference between the ordered and received/delivered quantities ant it
ioritz@18421
   762
        -- updates the m_storage_pending.
ioritz@18421
   763
        IF (v_DocAction='CL') THEN
ioritz@18421
   764
          -- Cancel undelivered Items
ioritz@18421
   765
          IF (v_isSoTrx='Y') THEN --Sales orders
ioritz@18421
   766
            FOR Cur_Inventory IN (
ioritz@18588
   767
              SELECT QtyInvoiced, QtyDelivered ,QtyOrdered, QuantityOrder, priceactual, gross_unit_price,
ioritz@18421
   768
	      
ioritz@18421
   769
	      C_ORDERLINE_ID AS ID,
ioritz@18421
   770
	      M_Product_ID,
ioritz@18421
   771
	      M_Warehouse_ID,
ioritz@18421
   772
	      M_AttributeSetInstance_ID,
ioritz@18421
   773
	      C_UOM_ID,
markmm82@30851
   774
             C_AUM,
ioritz@18421
   775
	      M_PRODUCT_UOM_ID,
ioritz@18421
   776
          C_Currency_ID
ioritz@18421
   777
	      FROM C_ORDERLINE
ioritz@18421
   778
	      WHERE C_Order_ID=v_Record_ID
ioritz@18421
   779
                AND QtyOrdered <> (SELECT (CASE WHEN (qtyinvoiced = 0) THEN QtyDelivered ELSE 
ioritz@18421
   780
			  	    (CASE WHEN (QtyDelivered = 0) THEN qtyinvoiced ELSE 
javier@17550
   781
					(CASE WHEN (QtyDelivered < 0 AND qtyinvoiced < 0) THEN LEAST(QtyDelivered, qtyinvoiced) ELSE GREATEST(QtyDelivered, qtyinvoiced) END) END) END)
ioritz@18421
   782
                                  FROM C_ORDERLINE COL
ioritz@18421
   783
                                  WHERE COL.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID)
javier@19482
   784
                AND m_product_id IS NOT NULL
ioritz@18421
   785
            )
ioritz@18421
   786
            LOOP
ioritz@18421
   787
              v_QtyOrdered := CASE WHEN (Cur_Inventory.QtyDelivered < 0) THEN LEAST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) ELSE GREATEST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) END;
atul@31807
   788
              v_QtyAum := M_GET_CONVERTED_AUMQTY(Cur_Inventory.M_Product_ID, v_QtyOrdered, Cur_Inventory.C_AUM);
ioritz@18588
   789
              v_linenetamt := ROUND(v_QtyOrdered * Cur_Inventory.priceactual, C_GET_CURRENCY_PRECISION(Cur_Inventory.C_Currency_ID, 'A'));
ioritz@18588
   790
              v_linegrossamt := ROUND(v_QtyOrdered * Cur_Inventory.gross_unit_price, C_GET_CURRENCY_PRECISION(Cur_Inventory.C_Currency_ID, 'A'));
ioritz@18421
   791
              SELECT MAX(UOM.C_UOM_ID)
ioritz@18421
   792
              INTO v_ProductUOM
ioritz@18421
   793
              FROM M_PRODUCT_UOM UOM 
ioritz@18421
   794
              WHERE UOM.M_PRODUCT_UOM_ID=Cur_Inventory.M_PRODUCT_UOM_ID;
david@30807
   795
              v_QuantityOrder := CASE WHEN Cur_Inventory.C_AUM IS NOT NULL OR (Cur_Inventory.C_AUM IS NULL AND Cur_Inventory.M_PRODUCT_UOM_ID IS NULL) THEN Cur_Inventory.QuantityOrder
david@30807
   796
                                 ELSE (c_uom_convert((CASE WHEN (Cur_Inventory.QtyDelivered < 0) THEN LEAST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) ELSE GREATEST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) END), 
david@30807
   797
              Cur_Inventory.C_UOM_ID, v_ProductUOM,'Y')) END;
ioritz@18421
   798
ioritz@18421
   799
              IF (Cur_Inventory.QtyOrdered <> v_QtyOrdered) THEN
ioritz@18421
   800
                M_UPDATE_STORAGE_PENDING(v_Client_ID, v_Org_ID, v_UpdatedBy, Cur_Inventory.M_Product_ID, Cur_Inventory.M_Warehouse_ID, Cur_Inventory.M_AttributeSetInstance_ID,
ioritz@18421
   801
                Cur_Inventory.C_UOM_ID, Cur_Inventory.M_PRODUCT_UOM_ID, -(Cur_Inventory.QtyOrdered - v_QtyOrdered), -(Cur_Inventory.QuantityOrder - v_QuantityOrder), 0, null);
ioritz@18421
   802
              END IF;
ioritz@18421
   803
ioritz@18421
   804
              -- UPDATE C_ORDERLINE
ioritz@18421
   805
              UPDATE C_ORDERLINE
ioritz@18421
   806
              SET QtyOrdered=v_QtyOrdered,
atul@31807
   807
                AumQty = v_QtyAum,
ioritz@18421
   808
                linenetamt=v_linenetamt,
ioritz@18588
   809
                line_gross_amount=v_linegrossamt,
ioritz@18421
   810
                QuantityOrder=v_QuantityOrder,
ioritz@18421
   811
                Updated=now()
ioritz@18421
   812
              WHERE C_ORDERLINE_ID = Cur_Inventory.ID;
ioritz@18421
   813
            END LOOP;
ioritz@18421
   814
            -- For Purchase orders, M_MatchPO table used. Notice that only delivered lines(C_Invoiceline_Id is null) using
ioritz@18421
   815
          ELSE
ioritz@18421
   816
            FOR Cur_Inventory IN (
ioritz@18421
   817
              SELECT 
ioritz@18421
   818
                COALESCE((SELECT SUM(CASE WHEN M_MATCHPO.M_INOUTLINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END)
ioritz@18421
   819
                FROM M_MATCHPO
ioritz@18421
   820
                WHERE M_MATCHPO.C_ORDERLINE_ID=C_ORDERLINE.C_ORDERLINE_ID), 0) AS QtyDelivered,
ioritz@18421
   821
		COALESCE((SELECT   SUM(CASE WHEN M_MATCHPO.C_INVOICELINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END)
ioritz@18421
   822
                FROM M_MATCHPO
ioritz@18421
   823
                WHERE M_MATCHPO.C_ORDERLINE_ID=C_ORDERLINE.C_ORDERLINE_ID), 0) AS QtyInvoiced,
ioritz@18421
   824
                QtyOrdered,
ioritz@18421
   825
                QuantityOrder,
ioritz@18421
   826
		priceactual,
ioritz@18588
   827
		gross_unit_price,
ioritz@18421
   828
		linenetamt,
ioritz@18421
   829
                C_ORDERLINE_ID AS ID,
ioritz@18421
   830
	        M_Product_ID,
ioritz@18421
   831
	        M_Warehouse_ID,
ioritz@18421
   832
	        M_AttributeSetInstance_ID,
ioritz@18421
   833
	        C_UOM_ID,
markmm82@30851
   834
               C_AUM,
ioritz@18421
   835
	        M_PRODUCT_UOM_ID,
ioritz@18421
   836
	        C_Currency_ID
ioritz@18421
   837
              FROM C_ORDERLINE
ioritz@18421
   838
              WHERE C_ORDERLINE.C_ORDER_ID=v_Record_ID
ioritz@18421
   839
                AND qtyordered <> COALESCE((
ioritz@18421
   840
                    SELECT (CASE WHEN (SUM(CASE WHEN M_MATCHPO.M_INOUTLINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END) = 0) 
javier@17550
   841
				THEN SUM(CASE WHEN M_MATCHPO.C_INVOICELINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END) ELSE 
javier@17550
   842
					(CASE WHEN (SUM(CASE WHEN M_MATCHPO.C_INVOICELINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END) = 0) 
javier@17550
   843
						THEN SUM(CASE WHEN M_MATCHPO.M_INOUTLINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END)  
javier@17550
   844
						ELSE (CASE WHEN (SUM(CASE WHEN M_MATCHPO.M_INOUTLINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END) < 0 AND SUM(CASE WHEN M_MATCHPO.C_INVOICELINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END) < 0)  
javier@17550
   845
							THEN LEAST(SUM(CASE WHEN M_MATCHPO.M_INOUTLINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END),SUM(CASE WHEN M_MATCHPO.C_INVOICELINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END)) 
javier@17550
   846
							ELSE GREATEST(SUM(CASE WHEN M_MATCHPO.M_INOUTLINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END),SUM(CASE WHEN M_MATCHPO.C_INVOICELINE_ID IS NULL THEN M_MATCHPO.QTY ELSE 0 END)) END) 
javier@17550
   847
					END)
javier@17550
   848
				END)
ioritz@18421
   849
                    FROM M_MATCHPO
ioritz@18421
   850
                    WHERE M_MATCHPO.C_ORDERLINE_ID=C_ORDERLINE.C_ORDERLINE_ID
ioritz@18421
   851
                    ), 0)
ioritz@18421
   852
            )
ioritz@18421
   853
            LOOP
collazoandy4@32164
   854
              v_QtyOrdered := COALESCE(CASE WHEN (Cur_Inventory.QtyDelivered < 0) THEN LEAST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) ELSE CASE WHEN (Cur_Inventory.QtyDelivered = 0) THEN Cur_Inventory.QtyInvoiced ELSE GREATEST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) END END, 0);
atul@31807
   855
              v_QtyAum := M_GET_CONVERTED_AUMQTY(Cur_Inventory.M_Product_ID, v_QtyOrdered, Cur_Inventory.C_AUM);
ioritz@18588
   856
              v_linenetamt := ROUND(COALESCE(v_QtyOrdered, 0) * Cur_Inventory.priceactual, C_GET_CURRENCY_PRECISION(Cur_Inventory.C_Currency_ID, 'A'));
ioritz@18588
   857
              v_linegrossamt := ROUND(COALESCE(v_QtyOrdered, 0) * Cur_Inventory.gross_unit_price, C_GET_CURRENCY_PRECISION(Cur_Inventory.C_Currency_ID, 'A'));
david@30807
   858
ioritz@18421
   859
              SELECT MAX(UOM.C_UOM_ID)
ioritz@18421
   860
              INTO v_ProductUOM
ioritz@18421
   861
              FROM M_PRODUCT_UOM UOM 
ioritz@18421
   862
              WHERE UOM.M_PRODUCT_UOM_ID=Cur_Inventory.M_PRODUCT_UOM_ID;
david@30807
   863
              v_QuantityOrder := CASE WHEN Cur_Inventory.C_AUM IS NOT NULL OR (Cur_Inventory.C_AUM IS NULL AND Cur_Inventory.M_PRODUCT_UOM_ID IS NULL) THEN Cur_Inventory.QuantityOrder
david@30807
   864
                                 ELSE (COALESCE(c_uom_convert((CASE WHEN (Cur_Inventory.QtyDelivered < 0) THEN LEAST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) ELSE GREATEST(Cur_Inventory.QtyDelivered, Cur_Inventory.QtyInvoiced) END),
david@30807
   865
              Cur_Inventory.C_UOM_ID, v_ProductUOM,'Y'), 0)) END;
ioritz@18421
   866
              IF (Cur_Inventory.QtyOrdered <> v_QtyOrdered) THEN
ioritz@18421
   867
                M_UPDATE_STORAGE_PENDING(v_Client_ID, v_Org_ID, v_UpdatedBy, Cur_Inventory.M_Product_ID, Cur_Inventory.M_Warehouse_ID, Cur_Inventory.M_AttributeSetInstance_ID,
ioritz@18421
   868
                Cur_Inventory.C_UOM_ID, Cur_Inventory.M_PRODUCT_UOM_ID, 0, null, -(Cur_Inventory.QtyOrdered - v_QtyOrdered), -(Cur_Inventory.QuantityOrder - v_QuantityOrder));
ioritz@18421
   869
              END IF;
ioritz@18421
   870
ioritz@18421
   871
              -- UPDATE C_ORDERLINE
ioritz@18421
   872
              UPDATE C_ORDERLINE
ioritz@18421
   873
              SET QtyOrdered=v_QtyOrdered,
atul@31807
   874
                AumQty = v_QtyAum,
ioritz@18421
   875
                linenetamt=v_linenetamt,
ioritz@18588
   876
                line_gross_amount=v_linegrossamt,
ioritz@18421
   877
                QuantityOrder=v_QuantityOrder,
ioritz@18421
   878
                Updated=now()
ioritz@18421
   879
              WHERE C_ORDERLINE_ID = Cur_Inventory.ID;
ioritz@18421
   880
            END LOOP;
ioritz@18421
   881
          END IF;
ioritz@18421
   882
          -- if there is no change, the tax calculation, etc. is not needed.
ioritz@18421
   883
          -- potential problem, if posted (i.e. encumbered) for full amount
ioritz@18421
   884
          -- and the rest then cancelled out.
carlos@0
   885
        END IF;
ioritz@18421
   886
      END;
gorkaion@14380
   887
gorkaion@14380
   888
      /**
gorkaion@14380
   889
      *Update Product purchasing Plan Table
gorkaion@14546
   890
      * Return Material orders do not update the last price.
gorkaion@14380
   891
      */
gorkaion@14546
   892
      IF (v_isSoTrx ='N' AND v_isreturndoctype = 'N') THEN
gorkaion@14380
   893
        FOR Cur_OrderLine IN (SELECT * FROM C_ORDERLINE WHERE C_Order_Id =  v_Record_ID)
gorkaion@14380
   894
        LOOP
harikrishnan@7824
   895
          UPDATE M_PRODUCT_PO SET PriceLastPO=Cur_OrderLine.PriceActual 
gorkaion@14390
   896
          Where C_BPARTNER_ID = v_CBPartner_ID AND M_PRODUCT_ID = Cur_OrderLine.M_PRODUCT_ID
harikrishnan@7824
   897
          AND Ad_Isorgincluded(Cur_OrderLine.AD_ORG_ID,AD_ORG_ID, Cur_OrderLine.AD_Client_ID) <> -1;
gorkaion@14380
   898
        END LOOP;
gorkaion@14380
   899
      END IF;
carlos@0
   900
      /**
carlos@0
   901
      * Void Order - prepare
carlos@0
   902
      */
gorkaion@14380
   903
      IF (v_DocAction='VO') THEN
carlos@0
   904
        -- Cancel all Items
carlos@0
   905
        UPDATE C_ORDERLINE
gorkaion@14390
   906
          SET QtyOrdered=0,
gorkaion@14390
   907
          --MODIFIED BY F.IRIAZABAL
david@30807
   908
          QuantityOrder = CASE WHEN C_AUM IS NOT NULL OR (C_AUM IS NULL AND M_PRODUCT_UOM_ID IS NULL) THEN NULL ELSE 0 END,
gorkaion@14390
   909
          LineNetAmt=0,
gorkaion@14390
   910
          Updated=now()
carlos@0
   911
        WHERE C_Order_ID=v_Record_ID
gorkaion@239
   912
          AND QtyOrdered<>0;
carlos@0
   913
      END IF;
gorkaion@14380
   914
gorkaion@14380
   915
     /**************************************************************************
carlos@0
   916
      * Start Processing ------------------------------------------------------
carlos@0
   917
      *************************************************************************/
asier@1929
   918
      -- Check the header belongs to a organization where transactions are posible and ready to use
asier@1929
   919
      SELECT AD_Org.IsReady, Ad_OrgType.IsTransactionsAllowed
gorkaion@14380
   920
        INTO v_is_ready, v_is_tr_allow
asier@1929
   921
      FROM C_ORDER, AD_Org, AD_OrgType
asier@1929
   922
      WHERE AD_Org.AD_Org_ID=C_ORDER.AD_Org_ID
gorkaion@14380
   923
        AND AD_Org.AD_OrgType_ID=AD_OrgType.AD_OrgType_ID
gorkaion@14380
   924
        AND C_ORDER.C_ORDER_ID=v_Record_ID;
asier@1929
   925
      IF (v_is_ready='N') THEN
asier@1929
   926
        RAISE_APPLICATION_ERROR(-20000, '@OrgHeaderNotReady@');
asier@1929
   927
      END IF;
asier@1929
   928
      IF (v_is_tr_allow='N') THEN
asier@1929
   929
        RAISE_APPLICATION_ERROR(-20000, '@OrgHeaderNotTransAllowed@');
asier@1929
   930
      END IF;
asier@1929
   931
      SELECT AD_ORG_CHK_DOCUMENTS('C_ORDER', 'C_ORDERLINE', v_Record_ID, 'C_ORDER_ID', 'C_ORDER_ID') INTO v_is_included FROM dual;
asier@1929
   932
      IF (v_is_included=-1) THEN
asier@1929
   933
        RAISE_APPLICATION_ERROR(-20000, '@LinesAndHeaderDifferentLEorBU@');
asier@1929
   934
      END IF;
gorkaion@14380
   935
gorkaion@14380
   936
      IF (p_PInstance_ID IS NOT NULL) THEN
carlos@0
   937
        v_ResultStr:='LockingOrder';
carlos@0
   938
        UPDATE C_ORDER  SET Processing='Y'  WHERE C_Order_ID=v_Record_ID;
carlos@0
   939
        COMMIT;
gorkaion@14380
   940
        -- Now, needs to go to END_PROCESSING to unlock
carlos@0
   941
      END IF;
carlos@0
   942
      /**
gorkaion@14390
   943
      * Allowed Actions:  AProve, COmplete, PRocess, CLose, VOid
carlos@0
   944
      */
gorkaion@14390
   945
      IF (v_DocAction IN('AP', 'CO', 'PR', 'CL', 'VO')) THEN
carlos@0
   946
        NULL;
carlos@0
   947
      ELSE
carlos@0
   948
        RAISE_APPLICATION_ERROR(-20000, '@ActionNotAllowedHere@') ;
carlos@0
   949
      END IF;
gorkaion@14380
   950
gorkaion@14390
   951
      SELECT COUNT(*)
gorkaion@14390
   952
        INTO v_count
carlos@0
   953
      FROM AD_CLIENTINFO
carlos@0
   954
      WHERE AD_CLIENT_ID=v_Client_ID
carlos@0
   955
        AND CHECKORDERORG='Y';
gorkaion@14380
   956
      IF (v_count > 0) THEN
carlos@0
   957
        v_ResultStr:='CheckingRestrictions - C_ORDER ORG IS IN C_BPARTNER ORG TREE';
carlos@0
   958
        SELECT COUNT(*)
gorkaion@14380
   959
          INTO v_count
gorkaion@14380
   960
        FROM C_ORDER c, C_BPARTNER bp
carlos@0
   961
        WHERE c.C_Order_ID=v_Record_ID
carlos@0
   962
          AND c.C_BPARTNER_ID=bp.C_BPARTNER_ID
carlos@0
   963
          AND Ad_Isorgincluded(c.AD_ORG_ID, bp.AD_ORG_ID, bp.AD_CLIENT_ID)=-1;
gorkaion@14380
   964
        IF (v_count > 0) THEN
carlos@0
   965
          RAISE_APPLICATION_ERROR(-20000, '@NotCorrectOrgBpartnerOrder@') ;
carlos@0
   966
        END IF;
carlos@0
   967
      END IF;
adrianromero@11736
   968
victor@3675
   969
     /**************************************************************************
asier@18349
   970
      * Calculate promotions                                                   
asier@18349
   971
      *************************************************************************/
miguel@23885
   972
      IF (v_DocAction = 'CO' AND v_isreturndoctype = 'N' AND v_recalculateDiscounts = 'Y') THEN
asier@18349
   973
         M_PROMOTION_CALCULATE('O', v_Record_ID, v_User);
asier@18349
   974
      END IF;
asier@18349
   975
asier@18349
   976
     /**************************************************************************
gorkaion@14380
   977
      * Calculate Discounts
gorkaion@14380
   978
      *************************************************************************/
adrianromero@11452
   979
miguel@23885
   980
      -- if sales order was created from quotation with "firm quotation" check
miguel@23885
   981
      -- then discounts are not recalculated
miguel@23885
   982
      IF (v_recalculateDiscounts = 'Y') THEN
miguel@23885
   983
        -- Delete first previous discounts (if possible) and then recalculate them
miguel@23885
   984
        UPDATE C_ORDER
miguel@23885
   985
        SET DocStatus='IP', -- In progress
miguel@23885
   986
            Processing='N',
miguel@23885
   987
            Processed='N',
miguel@23885
   988
            Updated=now(),
miguel@23885
   989
            UpdatedBy=v_User
miguel@23885
   990
        WHERE C_Order_ID=v_Record_ID;
adrianromero@11452
   991
miguel@23885
   992
        DELETE
miguel@23885
   993
        FROM C_ORDERLINE
miguel@23885
   994
        WHERE C_ORDER_DISCOUNT_ID IS NOT NULL
miguel@23885
   995
          AND C_ORDER_ID = v_Record_ID
miguel@23885
   996
          AND NOT EXISTS (SELECT C_INVOICELINE_ID FROM C_INVOICELINE WHERE C_INVOICELINE.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID)
miguel@23885
   997
          AND NOT EXISTS (SELECT M_INOUTLINE_ID FROM M_INOUTLINE WHERE M_INOUTLINE.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID)
miguel@23885
   998
          AND NOT EXISTS (SELECT M_MATCHPO_ID FROM M_MATCHPO WHERE M_MATCHPO.C_ORDERLINE_ID = C_ORDERLINE.C_ORDERLINE_ID);
adrianromero@11736
   999
miguel@23885
  1000
        UPDATE C_ORDERLINE
miguel@23885
  1001
        SET pricelist = 0, priceactual = 0, pricelimit = 0, linenetamt = 0, pricestd = 0
miguel@23885
  1002
        WHERE C_ORDER_DISCOUNT_ID IS NOT NULL
miguel@23885
  1003
          AND C_ORDER_ID=v_Record_ID;
adrianromero@11736
  1004
miguel@23885
  1005
        UPDATE C_ORDER
miguel@23885
  1006
        SET DocStatus=v_DocStatus, -- restore
miguel@23885
  1007
            Processing=v_IsProcessing,
miguel@23885
  1008
            Processed=v_IsProcessed,
miguel@23885
  1009
            Updated=now(),
miguel@23885
  1010
            UpdatedBy=v_User
miguel@23885
  1011
        WHERE C_Order_ID=v_Record_ID;
adrianromero@11736
  1012
miguel@23885
  1013
        v_CumDiscount:=0;
miguel@23885
  1014
        v_OldCumDiscount:=0;
miguel@23885
  1015
        v_Line:=10;
miguel@23885
  1016
        SELECT MAX(LINE)
miguel@23885
  1017
          INTO v_OrderLineSeqNo
miguel@23885
  1018
        FROM C_ORDERLINE
miguel@23885
  1019
        WHERE C_ORDER_ID=v_Record_ID;
miguel@23885
  1020
        FOR Cur_COrderDiscount IN
miguel@23885
  1021
           (SELECT C_ORDER_DISCOUNT.C_ORDER_DISCOUNT_ID, C_DISCOUNT.DISCOUNT, C_DISCOUNT.M_PRODUCT_ID, C_DISCOUNT.NAME,
miguel@23885
  1022
              C_ORDER_DISCOUNT.CASCADE, C_DISCOUNT.C_DISCOUNT_ID, M_PRODUCT.C_UOM_ID
miguel@23885
  1023
            FROM C_ORDER_DISCOUNT, C_DISCOUNT, M_PRODUCT
miguel@23885
  1024
            WHERE C_ORDER_DISCOUNT.C_DISCOUNT_ID=C_DISCOUNT.C_DISCOUNT_ID
miguel@23885
  1025
              AND C_DISCOUNT.M_PRODUCT_ID=M_PRODUCT.M_PRODUCT_ID
miguel@23885
  1026
              AND C_ORDER_DISCOUNT.C_ORDER_ID=v_Record_ID
miguel@23885
  1027
              AND C_ORDER_DISCOUNT.ISACTIVE='Y'
miguel@23885
  1028
              AND C_DISCOUNT.ISACTIVE='Y'
miguel@23885
  1029
            ORDER BY C_ORDER_DISCOUNT.LINE
victor@3675
  1030
            )
gorkaion@14380
  1031
        LOOP
miguel@23885
  1032
          v_CumDiscount:=(1-v_OldCumDiscount) * Cur_COrderDiscount.Discount/100;
miguel@23885
  1033
          v_OldCumDiscount:=v_OldCumDiscount + v_CumDiscount;
miguel@23885
  1034
          FOR Cur_TaxDiscount IN
miguel@23885
  1035
             (SELECT C_ORDERLINE.C_TAX_ID,
miguel@23885
  1036
                SUM(C_ORDERLINE.LINENETAMT) AS LINENETAMT,
miguel@23885
  1037
                SUM(C_ORDERLINE.LINE_GROSS_AMOUNT) AS LINEGROSSAMT
miguel@23885
  1038
              FROM C_ORDERLINE
miguel@23885
  1039
              WHERE C_ORDER_ID=v_Record_ID
miguel@23885
  1040
                AND C_ORDERLINE.LINENETAMT<>0
miguel@23885
  1041
                AND C_ORDER_DISCOUNT_ID IS NULL
miguel@23885
  1042
              GROUP BY C_TAX_ID
miguel@23885
  1043
              )
miguel@23885
  1044
          LOOP
miguel@23885
  1045
            IF (v_istaxincluded = 'Y') THEN
miguel@23885
  1046
              IF (Cur_COrderDiscount.CASCADE='Y') THEN
miguel@23885
  1047
                v_line_gross_amount:=(-1) * Cur_TaxDiscount.LINEGROSSAMT * v_CumDiscount;
miguel@23885
  1048
              ELSE
miguel@23885
  1049
                v_line_gross_amount:=(-1) * Cur_TaxDiscount.LINEGROSSAMT * Cur_COrderDiscount.Discount/100;
miguel@23885
  1050
              END IF;
alvaro@31665
  1051
              v_Discount:= C_GET_NET_AMOUNT_FROM_GROSS(Cur_TaxDiscount.C_TAX_ID, v_line_gross_amount, 0, v_stdPrecision);
miguel@23885
  1052
              v_gross_unit_price:= v_line_gross_amount;
mikel@17452
  1053
            ELSE
miguel@23885
  1054
              IF (Cur_COrderDiscount.CASCADE='Y') THEN
miguel@23885
  1055
                v_Discount:=(-1) * Cur_TaxDiscount.LINENETAMT * v_CumDiscount;
miguel@23885
  1056
              ELSE
miguel@23885
  1057
                v_Discount:=(-1) * Cur_TaxDiscount.LINENETAMT * Cur_COrderDiscount.Discount/100;
miguel@23885
  1058
              END IF;
miguel@23885
  1059
              v_gross_unit_price:= 0;
miguel@23885
  1060
              v_line_gross_amount:= 0;
mikel@17452
  1061
            END IF;
adrianromero@11736
  1062
miguel@23885
  1063
            SELECT COUNT(*) INTO v_DiscountExist FROM C_ORDERLINE
adrianromero@11736
  1064
            WHERE C_ORDERLINE.C_ORDER_DISCOUNT_ID = Cur_COrderDiscount.C_ORDER_DISCOUNT_ID
gorkaion@14380
  1065
              AND C_ORDERLINE.C_TAX_ID = Cur_TaxDiscount.C_TAX_ID;
miguel@23885
  1066
miguel@23885
  1067
            IF (v_DiscountExist = 0) THEN
miguel@23885
  1068
              v_OrderLineSeqNo:=10 + v_OrderLineSeqNo;
miguel@23885
  1069
              v_OrderLine:=get_uuid();
miguel@23885
  1070
              INSERT INTO c_orderline
miguel@23885
  1071
                (
miguel@23885
  1072
                  c_orderline_id, ad_client_id, ad_org_id, isactive, created, createdby,
miguel@23885
  1073
                  updated, updatedby, c_order_id, line, c_bpartner_id, c_bpartner_location_id,
miguel@23885
  1074
                  dateordered, datepromised, datedelivered, dateinvoiced, description,
miguel@23885
  1075
                  m_product_id, m_warehouse_id, directship, c_uom_id, qtyordered,
miguel@23885
  1076
                  qtyreserved, qtydelivered, qtyinvoiced, m_shipper_id, c_currency_id,
miguel@23885
  1077
                  pricelist, priceactual, pricelimit, linenetamt, discount, freightamt,
miguel@23885
  1078
                  c_charge_id, chargeamt, c_tax_id, s_resourceassignment_id, ref_orderline_id,
david@30807
  1079
                  m_attributesetinstance_id, isdescription, quantityorder, m_product_uom_id, aumqty, c_aum,
miguel@23885
  1080
                  m_offer_id, pricestd, C_ORDER_DISCOUNT_ID,
miguel@23885
  1081
                  gross_unit_price, taxbaseamt,line_gross_amount
miguel@23885
  1082
                )
miguel@23885
  1083
              VALUES
miguel@23885
  1084
                (
miguel@23885
  1085
                  v_OrderLine, v_Client_ID, v_Org_ID, 'Y', now(), v_UpdatedBy,
miguel@23885
  1086
                  now(), v_UpdatedBy, v_Record_ID, v_OrderLineSeqNo, NULL, NULL,
miguel@23885
  1087
                  now(), now(), now(), now(), Cur_COrderDiscount.NAME,
miguel@23885
  1088
                  Cur_COrderDiscount.M_PRODUCT_ID, v_M_Warehouse_ID, 'N', Cur_COrderDiscount.C_UOM_ID, 1,
miguel@23885
  1089
                  0, 0, 0, NULL, v_c_currency_id,
alvaro@31651
  1090
                  ROUND(v_Discount, v_pricePrecision), ROUND(v_Discount, v_pricePrecision), ROUND(v_Discount, v_pricePrecision), ROUND(v_Discount, v_pricePrecision), 0, 0,
miguel@23885
  1091
                  NULL, NULL, Cur_TaxDiscount.C_TAX_ID, NULL, NULL,
david@30807
  1092
                  NULL, 'N', NULL, NULL, NULL, NULL,
alvaro@31651
  1093
                  NULL, ROUND(v_Discount, v_pricePrecision), NULL,
alvaro@31651
  1094
                  ROUND(v_gross_unit_price, v_pricePrecision), ROUND(v_Discount, v_pricePrecision),ROUND(v_line_gross_amount, v_pricePrecision)
miguel@23885
  1095
                );
miguel@23885
  1096
miguel@23885
  1097
              UPDATE C_ORDERLINE
miguel@23885
  1098
              SET C_ORDER_DISCOUNT_ID=Cur_COrderDiscount.C_ORDER_DISCOUNT_ID
miguel@23885
  1099
              WHERE C_ORDERLINE_ID=v_OrderLine;
miguel@23885
  1100
            ELSE
miguel@23885
  1101
              UPDATE C_ORDERLINE 
alvaro@31651
  1102
              SET pricelist = ROUND(v_Discount, v_pricePrecision), priceactual = ROUND(v_Discount, v_pricePrecision), pricelimit = ROUND(v_Discount, v_pricePrecision), linenetamt = ROUND(v_Discount, v_pricePrecision), pricestd = ROUND(v_Discount, v_pricePrecision)
miguel@23885
  1103
              WHERE C_ORDERLINE.C_ORDER_DISCOUNT_ID = Cur_COrderDiscount.C_ORDER_DISCOUNT_ID
miguel@23885
  1104
                AND C_ORDERLINE.C_TAX_ID = Cur_TaxDiscount.C_TAX_ID;
miguel@23885
  1105
            END IF;
miguel@23885
  1106
          END LOOP;
miguel@23885
  1107
          v_Line:=v_Line + 10;
gorkaion@14380
  1108
        END LOOP;
miguel@23885
  1109
      END IF;
victor@3675
  1110
carlos@0
  1111
      /**
carlos@0
  1112
      * Convert to Target DocType
carlos@0
  1113
      */
carlos@0
  1114
      DECLARE
asier@2586
  1115
        v_DocSubTypeSO_Target VARCHAR(60) ;
carlos@0
  1116
      BEGIN
carlos@0
  1117
        v_ResultStr:='ConvertingDocType';
gorkaion@14380
  1118
        IF (v_DocType_ID <> v_DocTypeTarget_ID) THEN
carlos@0
  1119
          -- New
gorkaion@14380
  1120
          IF (v_DocStatus='DR' OR v_DocType_ID='0') THEN
carlos@0
  1121
            -- Update to Target Document Type
gorkaion@239
  1122
            WHILE(v_DocType_ID<>v_DocTypeTarget_ID)
carlos@0
  1123
            LOOP
gorkaion@14380
  1124
              BEGIN
gorkaion@14380
  1125
                v_ResultStr:='UpdateDocType';
gorkaion@14380
  1126
                UPDATE C_ORDER
gorkaion@14380
  1127
                SET C_DocType_ID=v_DocTypeTarget_ID,
gorkaion@14380
  1128
                    Updated=now(),
gorkaion@14380
  1129
                    UpdatedBy=v_User
gorkaion@14380
  1130
                WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1131
                v_DocType_ID:=v_DocTypeTarget_ID;
gorkaion@14380
  1132
              EXCEPTION
gorkaion@14380
  1133
              WHEN OTHERS THEN
gorkaion@14380
  1134
                v_ResultStr:='UpdateDocumentNo';
gorkaion@14380
  1135
                UPDATE C_ORDER  SET DocumentNo=DocumentNo || '.'  WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1136
              END;
gorkaion@14380
  1137
            END LOOP;
gorkaion@14380
  1138
          ELSE
gorkaion@14380
  1139
            v_ResultStr:='GetTargetDocType';
gorkaion@14380
  1140
            SELECT DocSubTypeSO
gorkaion@14380
  1141
              INTO v_DocSubTypeSO_Target
gorkaion@14380
  1142
            FROM C_DOCTYPE
gorkaion@14380
  1143
            WHERE C_DocType_ID=v_DocTypeTarget_ID;
gorkaion@14380
  1144
            DBMS_OUTPUT.PUT_LINE('Changing DocType from ' || v_DocSubTypeSO || ' to ' || v_DocSubTypeSO_Target) ;
gorkaion@14380
  1145
            -- Change Offer to anything, Change InProcess to anything
gorkaion@14380
  1146
            IF (v_DocSubTypeSO IN('ON', 'OB') OR v_DocStatus='IP') THEN
gorkaion@14380
  1147
              -- Update to Target Document Type
gorkaion@14380
  1148
              WHILE(v_DocType_ID<>v_DocTypeTarget_ID)
gorkaion@14380
  1149
              LOOP
gorkaion@14380
  1150
                BEGIN
gorkaion@14380
  1151
                  v_ResultStr:='UpdateDocType';
gorkaion@14380
  1152
                  UPDATE C_ORDER
gorkaion@14380
  1153
                  SET C_DocType_ID=v_DocTypeTarget_ID,
gorkaion@14380
  1154
                      Updated=now(),
gorkaion@14380
  1155
                      UpdatedBy=v_User
gorkaion@14380
  1156
                  WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1157
                  v_DocType_ID:=v_DocTypeTarget_ID;
gorkaion@14380
  1158
                EXCEPTION
gorkaion@14380
  1159
                WHEN OTHERS THEN
gorkaion@14380
  1160
                  v_ResultStr:='UpdateDocumentNo';
gorkaion@14380
  1161
                  UPDATE C_ORDER  SET DocumentNo=DocumentNo || '.'  WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1162
                END;
gorkaion@14380
  1163
              END LOOP;
gorkaion@14380
  1164
            ELSE
gorkaion@14380
  1165
              -- Change Back
carlos@0
  1166
              UPDATE C_ORDER
gorkaion@14380
  1167
                SET C_DocTypeTarget_ID=v_DocType_ID
gorkaion@14380
  1168
              WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1169
              RAISE_APPLICATION_ERROR(-20000, '@CannotChangeDocType@') ;
gorkaion@14380
  1170
            END IF;
gorkaion@14380
  1171
          END IF;
gorkaion@14380
  1172
        END IF; -- C_DocType_ID <> C_DocTypeTarget_ID
gorkaion@14380
  1173
      END; -- Conversion
gorkaion@14380
  1174
gorkaion@14380
  1175
    /**
gorkaion@14380
  1176
      * Get DocSubTypeSO + Is it Binding :1:2
gorkaion@14380
  1177
      */
gorkaion@14380
  1178
      v_ResultStr:='TestBinding DocType_ID=' || v_DocType_ID;
gorkaion@14380
  1179
      SELECT CASE DocSubTypeSO WHEN 'ON' THEN 'N' ELSE 'Y' END, DocSubTypeSO
gorkaion@14380
  1180
        INTO v_IsBinding, v_DocSubTypeSO
gorkaion@14380
  1181
      FROM C_DOCTYPE
gorkaion@14380
  1182
      WHERE C_DocType_ID=v_DocType_ID;
gorkaion@14380
  1183
      DBMS_OUTPUT.PUT_LINE('DocSubTypeSO=' || v_DocSubTypeSO || ' IsBinding=' || v_IsBinding) ;
gorkaion@14380
  1184
gorkaion@14380
  1185
    /**************************************************************************
gorkaion@14380
  1186
      * Resolve not-stocked BOMs
gorkaion@14380
  1187
      *************************************************************************/
gorkaion@14380
  1188
      DECLARE
gorkaion@14380
  1189
        -- Order Lines with non-stocked BOMs
gorkaion@14380
  1190
        CUR_BOM_Line RECORD;
gorkaion@14380
  1191
      BEGIN
naiara@19828
  1192
        FOR CUR_BOM_Line IN
naiara@19828
  1193
          (SELECT l.c_orderline_id
naiara@19828
  1194
           FROM C_ORDERLINE l
naiara@19828
  1195
           WHERE l.C_Order_ID=v_Record_ID
naiara@19828
  1196
             AND l.IsActive='Y'
naiara@19828
  1197
             AND l.explode='N'
naiara@19828
  1198
             AND EXISTS
gorkaion@14380
  1199
               (SELECT *
gorkaion@14380
  1200
                FROM M_PRODUCT p
gorkaion@14380
  1201
                WHERE l.M_Product_ID=p.M_Product_ID
gorkaion@14380
  1202
                  AND p.IsBOM='Y'
gorkaion@14380
  1203
                  AND p.IsStocked='N'
gorkaion@14380
  1204
                )
naiara@19828
  1205
              ORDER BY l.Line
gorkaion@14380
  1206
             )
naiara@19828
  1207
        LOOP
naiara@19828
  1208
          M_EXPLODEBOMNOTSTOCK(null, CUR_BOM_Line.c_orderline_ID);
naiara@19828
  1209
        END LOOP;
gorkaion@14380
  1210
      END;
gorkaion@14380
  1211
    /**************************************************************************
gorkaion@14380
  1212
      * Always check and (un) Reserve Inventory  (counterpart: M_InOut_Post)
gorkaion@14380
  1213
      *************************************************************************/
ioritz@18421
  1214
      IF (v_DocAction<>'CL') THEN
ioritz@18421
  1215
        DECLARE
ioritz@18421
  1216
          Cur_ResLine RECORD;
gorkaion@14380
  1217
ioritz@18421
  1218
          v_QtySO       NUMBER; -- Reserved
ioritz@18421
  1219
          v_QtyOrderSO  NUMBER;
ioritz@18421
  1220
          v_QtyPO       NUMBER; -- Ordered
ioritz@18421
  1221
          v_QtyOrderPO  NUMBER;
alvaro@29579
  1222
          v_UOM_ID      VARCHAR2(32);
ioritz@18421
  1223
        BEGIN
ioritz@18421
  1224
          v_ResultStr := 'ReserveInventory';
ioritz@18421
  1225
          -- For all lines needing reservation
ioritz@18421
  1226
          FOR Cur_ResLine IN (SELECT l.M_Warehouse_ID, l.M_Product_ID, l.M_AttributeSetInstance_ID, l.C_OrderLine_ID,
ioritz@18421
  1227
                -- Target Level = 0 if DirectShip='Y' or Binding='N'
ioritz@18421
  1228
                (CASE l.DirectShip WHEN 'Y' THEN 0 ELSE (CASE v_IsBinding WHEN 'N' THEN 0 ELSE l.QtyOrdered END) END)
ioritz@18421
  1229
                 -l.QtyReserved-l.QtyDelivered AS Qty, l.QUANTITYORDER,
david@30807
  1230
                l.QtyReserved, l.QtyDelivered, l.DatePromised, l.C_UOM_ID, l.C_AUM,
ioritz@18421
  1231
                l.M_PRODUCT_UOM_ID
ioritz@18421
  1232
              FROM C_ORDERLINE l, M_PRODUCT p
ioritz@18421
  1233
              WHERE l.C_Order_ID=v_Record_ID
ioritz@18421
  1234
                -- Reserve Products (not: services, null products) --
ioritz@18421
  1235
                AND l.M_Product_ID=p.M_Product_ID
ioritz@18421
  1236
                AND p.IsStocked='Y' AND p.ProductType='I'
ioritz@18421
  1237
                -- Target Level = 0 if DirectShip='Y' or Binding='N'
ioritz@18421
  1238
                AND (CASE l.DirectShip WHEN 'Y' THEN 0 ELSE (CASE v_IsBinding WHEN 'N' THEN 0 ELSE l.QtyOrdered END)END)
sandra@25652
  1239
                -l.QtyReserved-l.QtyDelivered <> 0)
ioritz@18421
  1240
          LOOP
ioritz@18421
  1241
          
ioritz@18421
  1242
            -- Qty corrected for SO/PO
ioritz@18421
  1243
            IF (v_DocSubTypeSO IS NOT NULL) THEN
ioritz@18421
  1244
              v_QtySO   := Cur_ResLine.Qty;
ioritz@18421
  1245
              v_QtyOrderSO := NULL;
ioritz@18421
  1246
              IF (Cur_ResLine.QtyReserved = 0 AND Cur_ResLine.QtyDelivered = 0) THEN
ioritz@18421
  1247
                v_QtyOrderSO := Cur_ResLine.QuantityOrder;
david@30807
  1248
              ELSIF (Cur_ResLine.C_AUM IS NULL AND Cur_ResLine.M_Product_UOM_ID IS NOT NULL) THEN
alvaro@29579
  1249
                SELECT c_uom_id
alvaro@29579
  1250
                INTO v_UOM_ID
alvaro@29579
  1251
                FROM m_product_uom
alvaro@29579
  1252
                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
alvaro@29579
  1253
                v_QtyOrderSO := C_Uom_Convert(v_QtySO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
ioritz@18421
  1254
              END IF;
ioritz@18421
  1255
              v_QtyPO   := 0;
ioritz@18421
  1256
              v_QtyOrderPO := NULL;
ioritz@18421
  1257
            ELSE -- PO
ioritz@18421
  1258
              v_QtySO := 0;
ioritz@18421
  1259
              v_QtyOrderSO := NULL;
ioritz@18421
  1260
              v_QtyPO := Cur_ResLine.Qty;
ioritz@18421
  1261
              v_QtyOrderPO := NULL;
ioritz@18421
  1262
              IF (Cur_ResLine.QtyReserved = 0 AND Cur_ResLine.QtyDelivered = 0) THEN
ioritz@18421
  1263
                v_QtyOrderPO := Cur_ResLine.QuantityOrder;
david@30807
  1264
              ELSIF (Cur_ResLine.C_AUM IS NULL AND Cur_ResLine.M_Product_UOM_ID IS NOT NULL) THEN
alvaro@29579
  1265
                SELECT c_uom_id
alvaro@29579
  1266
                INTO v_UOM_ID
alvaro@29579
  1267
                FROM m_product_uom
alvaro@29579
  1268
                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
alvaro@29579
  1269
                v_QtyOrderPO := C_Uom_Convert(v_QtyPO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
ioritz@18421
  1270
              END IF;
gorkaion@14380
  1271
            END IF;
jon@21226
  1272
            IF ((v_DocStatus<>'IP' OR v_DocAction<>'CO') AND COALESCE(v_DocSubTypeSO, '')<>'OB') THEN
ioritz@18421
  1273
              M_UPDATE_STORAGE_PENDING(v_Client_ID, v_Org_ID, v_UpdatedBy, Cur_ResLine.M_Product_ID, Cur_ResLine.M_Warehouse_ID, Cur_ResLine.M_AttributeSetInstance_ID,
ioritz@18421
  1274
              Cur_ResLine.C_UOM_ID, Cur_ResLine.M_PRODUCT_UOM_ID, v_QtySO, v_QtyOrderSO, v_QtyPO, v_QtyOrderPO);
gorkaion@14380
  1275
            END IF;
ioritz@18421
  1276
            DBMS_OUTPUT.PUT_LINE('Reserved Warehouse=' || Cur_ResLine.M_Warehouse_ID || ', Product=' || Cur_ResLine.M_Product_ID || ', Attrib=' || Cur_ResLine.M_AttributeSetInstance_ID || ', Qty=' || v_QtySO || '/' || v_QtyPO);
gorkaion@14380
  1277
ioritz@18421
  1278
            -- Update Order Line
ioritz@18421
  1279
            IF (v_DocSubTypeSO IS NOT NULL) THEN
ioritz@18421
  1280
              UPDATE C_ORDERLINE
ioritz@18421
  1281
              SET QtyReserved = QtyReserved + v_QtySO
ioritz@18421
  1282
              WHERE C_OrderLine_ID = Cur_ResLine.C_OrderLine_ID;
gorkaion@14380
  1283
            END IF;
ioritz@18421
  1284
             rowcount:=SQL%ROWCOUNT;
ioritz@18421
  1285
            IF (rowcount <> 1) THEN
ioritz@18421
  1286
              IF (p_PInstance_ID IS NOT NULL) THEN
ioritz@18421
  1287
                ROLLBACK;
ioritz@18421
  1288
                v_ResultStr := 'LockingOrder';
ioritz@18421
  1289
                UPDATE C_ORDER
ioritz@18421
  1290
                SET Processing = 'N',
ioritz@18421
  1291
                Updated=now(),
ioritz@18421
  1292
                UpdatedBy=v_User
ioritz@18421
  1293
                WHERE C_Order_ID = v_Record_ID;
ioritz@18421
  1294
                RAISE NO_DATA_FOUND;
ioritz@18421
  1295
                COMMIT;
ioritz@18421
  1296
              END IF;
ioritz@18421
  1297
              RAISE_APPLICATION_ERROR(-20000, '@20011@');
ioritz@18421
  1298
            END IF;
ioritz@18421
  1299
          END LOOP; -- For all lines needing reservation
ioritz@18421
  1300
        END;
ioritz@18421
  1301
      END IF; -- Reserve Inventory
javier@17550
  1302
gorkaion@18662
  1303
     /**************************************************************************
gorkaion@18717
  1304
      * Stock Reservations management.
gorkaion@18662
  1305
      *************************************************************************/
gorkaion@18749
  1306
      SELECT COUNT(1) INTO v_count
gorkaion@18749
  1307
      FROM ad_preference
gorkaion@18749
  1308
      WHERE property = 'StockReservations';
gorkaion@18749
  1309
      IF (v_count > 0) THEN
gorkaion@18749
  1310
        IF (v_count > 1) THEN
david@34188
  1311
          v_dummy := AD_GET_PREFERENCE_VALUE('StockReservations', 'Y', v_client_id, v_org_id, v_User, NULL, NULL);
alvaro@33879
  1312
          DBMS_OUTPUT.PUT_LINE('StockReservations preference value: ' || v_dummy);
gorkaion@18749
  1313
        END IF;
gorkaion@18749
  1314
        DECLARE
gorkaion@18749
  1315
          v_reservation_id      VARCHAR2(32);
gorkaion@18749
  1316
          v_quantity            NUMBER;
gorkaion@18749
  1317
          v_reservedqty         NUMBER;
gorkaion@18749
  1318
          v_releasedqty         NUMBER;
gorkaion@18749
  1319
          v_allocated           NUMBER;
gorkaion@18749
  1320
          v_pendingtounreserve  NUMBER;
gorkaion@18749
  1321
          v_qtyaux              NUMBER;
gorkaion@18749
  1322
          v_res_status          M_RESERVATION.RES_STATUS%TYPE;
gorkaion@18749
  1323
          v_linecount           NUMBER;
gorkaion@18749
  1324
          v_creservedcount      NUMBER;
gorkaion@18749
  1325
          v_preservedcount      NUMBER;
gorkaion@18749
  1326
          
gorkaion@18749
  1327
          cur_res_stock         RECORD;
gorkaion@18749
  1328
        BEGIN
gorkaion@18749
  1329
          IF (v_issotrx = 'Y') THEN
gorkaion@18749
  1330
            FOR cur_orderline IN (
gorkaion@18749
  1331
                SELECT ol.c_orderline_id, ol.create_reservation, ol.qtyordered
gorkaion@18749
  1332
                FROM c_orderline ol
gorkaion@18749
  1333
                    JOIN m_product p ON ol.m_product_id = p.m_product_id
carlos@20773
  1334
                    LEFT JOIN m_reservation r ON ol.c_orderline_id = r.c_orderline_id
gorkaion@18749
  1335
                WHERE ol.c_order_id = v_record_id
carlos@20773
  1336
                  AND ((
carlos@20773
  1337
                      ol.qtyordered > 0
carlos@20773
  1338
                      AND p.isstocked = 'Y'
carlos@20773
  1339
                      AND p.producttype = 'I'
carlos@20773
  1340
                    ) OR (
carlos@20773
  1341
                      r.m_reservation_id IS NOT NULL
carlos@20773
  1342
                    )
carlos@20773
  1343
                  )
gorkaion@18749
  1344
            ) LOOP
gorkaion@18749
  1345
              SELECT count(*), max(m_reservation_id)
markmm82@30002
  1346
              INTO v_aux, v_reservation_id
gorkaion@18749
  1347
              FROM m_reservation
markmm82@30002
  1348
              WHERE c_orderline_id = cur_orderline.c_orderline_id
markmm82@30002
  1349
              AND res_status <> 'CL';
gorkaion@18749
  1350
              -- Initialize so_res_status
gorkaion@18749
  1351
              UPDATE c_orderline
gorkaion@18749
  1352
              SET so_res_status = 'NR'
gorkaion@18749
  1353
              WHERE c_orderline_id = cur_orderline.c_orderline_id;
gorkaion@18749
  1354
              IF (v_aux > 1) THEN
gorkaion@18749
  1355
                RAISE_APPLICATION_ERROR(-20000, '@SOLineWithMoreThanOneOpenReservation@');
gorkaion@18749
  1356
              ELSIF (v_aux = 1) THEN
gorkaion@18749
  1357
                -- Update reservation when possible.
gorkaion@18749
  1358
                -- Read reservation.
gorkaion@18749
  1359
                SELECT r.quantity, r.reservedqty, r.releasedqty, r.res_status,
gorkaion@18749
  1360
                      COALESCE(SUM(CASE rs.isallocated WHEN 'Y' THEN rs.quantity - COALESCE(rs.releasedqty, 0) ELSE 0 END), 0)
gorkaion@18749
  1361
                  INTO v_quantity, v_reservedqty, v_releasedqty, v_res_status,
gorkaion@18749
  1362
                      v_allocated
gorkaion@18749
  1363
                FROM m_reservation r
gorkaion@18749
  1364
                    LEFT JOIN m_reservation_stock rs ON r.m_reservation_id = rs.m_reservation_id
gorkaion@18749
  1365
                WHERE r.m_reservation_id = v_reservation_id
gorkaion@18749
  1366
                GROUP BY r.quantity, r.reservedqty, r.releasedqty, r.res_status;
gorkaion@18749
  1367
                IF (v_quantity != cur_orderline.qtyordered) THEN
m@28834
  1368
                  IF (v_allocated <> 0) THEN
gorkaion@18749
  1369
                    RAISE_APPLICATION_ERROR(-20000, '@ThereIsMoreAllocatedQtyThanOrdered@');
gorkaion@18749
  1370
                  END IF;
gorkaion@18749
  1371
                  IF (cur_orderline.qtyordered < v_releasedqty) THEN
gorkaion@18749
  1372
                    RAISE_APPLICATION_ERROR(-20000, '@CannotOrderLessThanReleasedQty@');
gorkaion@18749
  1373
                  END IF;
collazoandy4@31753
  1374
                  IF (cur_orderline.qtyordered < v_reservedqty) OR (v_releasedqty = 0 AND cur_orderline.qtyordered > 0) THEN
gorkaion@18749
  1375
                    --Reservation quantity to decrease with more reserved quantity than new quantity, unreserve stock
gorkaion@18749
  1376
                    v_pendingtounreserve := v_reservedqty - cur_orderline.qtyordered;
gorkaion@18749
  1377
                    FOR cur_res_stock IN (
gorkaion@18749
  1378
                        SELECT m_reservation_stock_id, quantity - COALESCE(releasedqty, 0) AS reservedqty
gorkaion@18749
  1379
                        FROM m_reservation_stock
gorkaion@18749
  1380
                        WHERE m_reservation_id = v_reservation_id
gorkaion@18749
  1381
                        ORDER BY COALESCE(releasedqty, 0), quantity - COALESCE(releasedqty, 0)
gorkaion@18749
  1382
                    ) LOOP
gorkaion@18749
  1383
                      v_qtyaux := LEAST(v_pendingtounreserve, cur_res_stock.reservedqty);
gorkaion@18749
  1384
                      UPDATE m_reservation_stock
gorkaion@18749
  1385
                      SET quantity = quantity - v_qtyaux,
gorkaion@18749
  1386
                          updated = now(),
gorkaion@18749
  1387
                          updatedby = v_user
gorkaion@18749
  1388
                      WHERE m_reservation_stock_id = cur_res_stock.m_reservation_stock_id;
gorkaion@18749
  1389
                      v_reservedqty := v_reservedqty - v_qtyaux;
gorkaion@18749
  1390
                      v_pendingtounreserve := v_pendingtounreserve - v_qtyaux;
gorkaion@18749
  1391
                      IF (v_pendingtounreserve = 0) THEN
gorkaion@18749
  1392
                        EXIT;
gorkaion@18749
  1393
                      END IF;
gorkaion@18749
  1394
                    END LOOP;
gorkaion@18749
  1395
                    IF (v_pendingtounreserve > 0) THEN
gorkaion@18749
  1396
                      RAISE_APPLICATION_ERROR(-20000, '@CouldNotUnreserveNeededQty@');
gorkaion@18749
  1397
                    END IF;
collazoandy4@32232
  1398
                    IF (v_DocAction <> 'CO') THEN
collazoandy4@32232
  1399
                      -- Delete reservation lines with zero releasedqty
collazoandy4@32232
  1400
                      DELETE FROM m_reservation_stock
collazoandy4@32232
  1401
                      WHERE COALESCE(releasedqty, 0) = 0
gorkaion@18749
  1402
                      AND m_reservation_id = v_reservation_id;
collazoandy4@32232
  1403
                    END IF;
gorkaion@18749
  1404
                  END IF;
collazoandy4@31753
  1405
                  -- Order line orderedqty greater than reservation releasedqty
collazoandy4@32232
  1406
                  IF (cur_orderline.qtyordered > v_releasedqty AND v_DocAction <> 'CO') THEN
collazoandy4@31753
  1407
                    UPDATE m_reservation_stock
collazoandy4@31753
  1408
                    SET quantity = releasedqty,
collazoandy4@31753
  1409
                        updated = now(),
collazoandy4@31753
  1410
                        updatedby = v_user
collazoandy4@31753
  1411
                    WHERE m_reservation_id = v_reservation_id;
collazoandy4@31753
  1412
                  END IF;
alvaro@31754
  1413
                  UPDATE m_reservation
alvaro@31754
  1414
                  SET quantity = cur_orderline.qtyordered,
collazoandy4@32232
  1415
                      res_status = CASE WHEN v_DocAction <> 'CO' THEN 'CL' ELSE res_status END,
alvaro@31754
  1416
                      updated = now(),
alvaro@31754
  1417
                      updatedby = v_user
alvaro@31754
  1418
                  WHERE m_reservation_id = v_reservation_id;
staff@34292
  1419
                  IF (v_quantity < cur_orderline.qtyordered AND v_res_status = 'CO' AND v_DocAction <> 'CO') THEN
gorkaion@18749
  1420
                    --Reservation processed with higher quantity. Try to reserve the new quantity.
gorkaion@18749
  1421
                    M_RESERVE_STOCK_AUTO(v_reservation_id, v_user, v_reservedqty);
gorkaion@18749
  1422
                  END IF;
gorkaion@18662
  1423
                END IF;
gorkaion@18749
  1424
                
gorkaion@18749
  1425
                IF (v_res_status <> 'DR') THEN
gorkaion@18749
  1426
                  -- Update so_res_status
gorkaion@18749
  1427
                  UPDATE c_orderline
gorkaion@18749
  1428
                  SET so_res_status = CASE WHEN cur_orderline.qtyordered = v_reservedqty THEN 'CR'
atul@24214
  1429
					   WHEN cur_orderline.qtyordered > v_reservedqty AND v_reservedqty > 0 THEN 'PR'
atul@24214
  1430
                                           ELSE 'NR'
gorkaion@18749
  1431
                                      END
gorkaion@18749
  1432
                  WHERE c_orderline_id = cur_orderline.c_orderline_id;
gorkaion@18662
  1433
                END IF;
markmm82@30002
  1434
              ELSE
markmm82@30002
  1435
                SELECT count(*)
markmm82@30002
  1436
                INTO v_aux
markmm82@30002
  1437
                FROM dual
markmm82@30002
  1438
                WHERE EXISTS (
markmm82@30002
  1439
                  SELECT 1
markmm82@30002
  1440
                  FROM m_reservation
markmm82@30002
  1441
                  WHERE c_orderline_id = cur_orderline.c_orderline_id
markmm82@30002
  1442
                );
markmm82@30002
  1443
                IF (v_aux = 0 AND cur_orderline.create_reservation = 'CRP') THEN
markmm82@30002
  1444
                  M_CREATE_RESERVE_FROM_SOL(cur_orderline.c_orderline_id, 'Y', v_user, v_reservation_id);
markmm82@30002
  1445
                ELSIF (v_aux = 0 AND cur_orderline.create_reservation = 'CR') THEN
markmm82@30002
  1446
                  M_CREATE_RESERVE_FROM_SOL(cur_orderline.c_orderline_id, 'N', v_user, v_reservation_id);
markmm82@30002
  1447
                END IF;
gorkaion@18662
  1448
              END IF;
gorkaion@18749
  1449
            END LOOP;
gorkaion@18749
  1450
            SELECT COUNT(*), SUM(CASE ol.so_res_status WHEN 'CR' THEN 1 ELSE 0 END), SUM(CASE ol.so_res_status WHEN 'PR' THEN 1 ELSE 0 END)
gorkaion@18749
  1451
              INTO v_linecount, v_creservedcount, v_preservedcount
gorkaion@18749
  1452
            FROM c_orderline ol
gorkaion@18749
  1453
                JOIN m_product p ON ol.m_product_id = p.m_product_id
gorkaion@18749
  1454
            WHERE ol.c_order_id = v_record_id
gorkaion@18749
  1455
              AND ol.qtyordered > 0
gorkaion@18749
  1456
              AND p.isstocked = 'Y'
gorkaion@18749
  1457
              AND p.producttype = 'I';
gorkaion@18749
  1458
            UPDATE c_order
gorkaion@18749
  1459
            SET so_res_status = CASE WHEN v_linecount = v_creservedcount THEN 'CR'
gorkaion@18749
  1460
                                     WHEN v_creservedcount + v_preservedcount > 0 THEN 'PR'
gorkaion@18749
  1461
                                     ELSE 'NR'
gorkaion@18749
  1462
                                END
gorkaion@18749
  1463
            WHERE c_order_id = v_record_id;
gorkaion@18749
  1464
          END IF;
gorkaion@18749
  1465
        END;
gorkaion@18749
  1466
      END IF;
adrianromero@27178
  1467
      
gorkaion@14380
  1468
      -- Synchronize Client/Org Ownership
gorkaion@14380
  1469
      UPDATE C_ORDERLINE
pandeeswari@18808
  1470
      SET AD_Client_ID=v_Client_ID
gorkaion@14380
  1471
      WHERE C_Order_ID=v_Record_ID
pandeeswari@18808
  1472
        AND (AD_Client_ID<>v_Client_ID) ;
gorkaion@14380
  1473
miguel@24752
  1474
      IF (v_docaction = 'CO' AND v_issotrx = 'N') THEN
miguel@24752
  1475
          UPDATE m_transaction
miguel@24752
  1476
          SET checkpricedifference = 'Y'
miguel@24752
  1477
          WHERE m_transaction_id IN (
miguel@24752
  1478
            SELECT trx.m_transaction_id 
miguel@24752
  1479
            FROM c_orderline  ol
miguel@24752
  1480
                 JOIN m_matchpo mpo ON mpo.c_orderline_id = ol.c_orderline_id
miguel@24752
  1481
                 JOIN m_transaction trx ON mpo.m_inoutline_id = trx.m_inoutline_id
miguel@24752
  1482
            WHERE trx.iscostcalculated = 'Y' AND  ol.c_order_id = v_record_id);
miguel@24752
  1483
      END IF;
miguel@24752
  1484
gorkaion@14380
  1485
    /**************************************************************************
gorkaion@14380
  1486
     * Order Complete:5 - Something to do:6
gorkaion@14380
  1487
     */
gorkaion@14380
  1488
      BEGIN
gorkaion@14380
  1489
        v_ResultStr:='OrderCompleteCheck';
victor@24222
  1490
        SELECT COUNT(*) INTO ToDeliverOrToInvoice FROM DUAL
victor@24210
  1491
        WHERE 0 <> ANY (select QtyOrdered - QtyDelivered from c_orderline where c_order_id = v_Record_ID)
victor@24210
  1492
        OR    0 <> ANY (select QtyOrdered - QtyInvoiced  from c_orderline where c_order_id = v_Record_ID);
victor@24222
  1493
        -- If something to deliver or to invoice, then ToDeliverOrToInvoice = 1
victor@24222
  1494
        IF (ToDeliverOrToInvoice = 0) THEN
gorkaion@14380
  1495
          DBMS_OUTPUT.PUT_LINE('OrderComplete') ;
gorkaion@14380
  1496
          IF (v_DocAction='CL') THEN
gorkaion@14380
  1497
            END_PROCESSING:=TRUE;
gorkaion@14380
  1498
          ELSIF (v_DocAction='VO') THEN
gorkaion@14380
  1499
            UPDATE C_ORDER
gorkaion@14380
  1500
            SET DocStatus='VO',
gorkaion@14380
  1501
                DocAction='--',
gorkaion@14380
  1502
                Processed='Y',
harikrishnan@7253
  1503
                Updated=now(),
gorkaion@14380
  1504
                UpdatedBy=v_User
gorkaion@14380
  1505
            WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1506
            END_PROCESSING:=TRUE;
gorkaion@14380
  1507
          ELSE
gorkaion@14380
  1508
            UPDATE C_ORDER
gorkaion@14380
  1509
            SET DocStatus='CO',
gorkaion@14380
  1510
                DocAction='--',
gorkaion@14380
  1511
                Processed='Y',
gorkaion@14380
  1512
                Updated=now(),
gorkaion@14380
  1513
                UpdatedBy=v_User
gorkaion@14380
  1514
            WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1515
            END_PROCESSING:=TRUE;
gorkaion@14380
  1516
          END IF;
gorkaion@14380
  1517
          IF (NOT END_PROCESSING) THEN
gorkaion@14380
  1518
            RAISE_APPLICATION_ERROR(-20000, '@AlreadyPosted@');
gorkaion@14380
  1519
          END IF;--END_PROCESSING
gorkaion@14380
  1520
        END IF;
gorkaion@14380
  1521
      END;
gorkaion@14380
  1522
    END IF;--FINISH_PROCESS
gorkaion@14380
  1523
    IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@14380
  1524
     /**
gorkaion@14380
  1525
      * In Progress -----------------------------------------------------------
gorkaion@14380
  1526
      */
gorkaion@14380
  1527
      UPDATE C_ORDER
gorkaion@14380
  1528
      SET DocStatus='IP',
gorkaion@14380
  1529
          DateAcct=DateOrdered,
gorkaion@14380
  1530
          Updated=now(),
gorkaion@14380
  1531
          UpdatedBy=v_User
gorkaion@14380
  1532
      WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1533
      IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@14380
  1534
        COMMIT;
gorkaion@14380
  1535
      END IF;
gorkaion@14380
  1536
gorkaion@14380
  1537
    /**
gorkaion@14380
  1538
      * Finished with processing
gorkaion@14380
  1539
      */
gorkaion@14380
  1540
      IF (v_DocAction='PR') THEN
gorkaion@14380
  1541
        v_ResultStr:='FinishProcessing';
gorkaion@14380
  1542
        UPDATE C_ORDER
gorkaion@14380
  1543
        SET DocStatus='IP',
gorkaion@14380
  1544
            DocAction='CO',
gorkaion@14380
  1545
            Processed='N',
gorkaion@14380
  1546
            Updated=now(),
gorkaion@14380
  1547
            UpdatedBy=v_User
gorkaion@14380
  1548
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1549
        -- C_Order_PickList(NULL, v_Record_ID);  -- Print PickList
gorkaion@14380
  1550
        END_PROCESSING:=TRUE;
gorkaion@14380
  1551
      END IF;
gorkaion@14380
  1552
    END IF;--FINISH_PROCESS
gorkaion@14380
  1553
    IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@14380
  1554
    /**************************************************************************
gorkaion@14380
  1555
      * Prepayment Order  Create Invoice
gorkaion@14380
  1556
      *************************************************************************/
gorkaion@14380
  1557
      IF (v_DocSubTypeSO='PR' AND v_DocStatus<>'WP') THEN
gorkaion@14380
  1558
        DBMS_OUTPUT.PUT_LINE('Create PreInvoice - ' || v_Record_ID) ;
gorkaion@14380
  1559
        v_ResultStr:='CreatePreInvoice';
gorkaion@14380
  1560
        C_Invoice_Create(NULL, Invoice_ID, v_Record_ID) ;
gorkaion@14380
  1561
        DBMS_OUTPUT.PUT_LINE('  PreInvoice - ' || Invoice_ID) ;
gorkaion@14380
  1562
        IF (Invoice_ID='0') THEN
gorkaion@14380
  1563
          RAISE_APPLICATION_ERROR(-20000, '@PreInvoiceCreateFailed@');
gorkaion@14380
  1564
        END IF;
gorkaion@14380
  1565
        C_INVOICE_POST(NULL, Invoice_ID) ;
gorkaion@14380
  1566
        --
gorkaion@14380
  1567
        UPDATE C_ORDER
gorkaion@14380
  1568
        SET DocStatus='WP',
gorkaion@14380
  1569
            DocAction='--',
gorkaion@14380
  1570
            Processed='Y',
gorkaion@14380
  1571
            Updated=now(),
gorkaion@14380
  1572
            UpdatedBy=v_User
gorkaion@14380
  1573
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1574
        --
gorkaion@14380
  1575
        END_PROCESSING:=TRUE;
gorkaion@14380
  1576
      END IF;
gorkaion@14380
  1577
      IF (NOT END_PROCESSING) THEN
gorkaion@14380
  1578
       /**
gorkaion@14380
  1579
        * Deliver Direct Shipments
gorkaion@14380
  1580
        */
gorkaion@14380
  1581
        v_ResultStr:='NonInventoryDelivery';
gorkaion@14380
  1582
        UPDATE C_ORDERLINE
gorkaion@14380
  1583
        SET QtyDelivered=QtyOrdered
gorkaion@14380
  1584
        WHERE DirectShip='Y'
gorkaion@14380
  1585
          AND C_Order_ID=v_Record_ID;
gorkaion@14380
  1586
      END IF;--END_PROCESSING
gorkaion@14380
  1587
    END IF;--FINISH_PROCESS
gorkaion@14380
  1588
    IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@14380
  1589
     /**************************************************************************
gorkaion@14380
  1590
      * Will-Call + Walk In Processing
gorkaion@14380
  1591
      * --
gorkaion@14380
  1592
      * (W)illCall(I)nvoice - (W)illCall(P)ickup - (W)alkIn(R)eceipt
gorkaion@14380
  1593
      * --
gorkaion@14380
  1594
      *************************************************************************/
gorkaion@14380
  1595
      IF (v_DocSubTypeSO IN('WI', 'WP', 'WR')) THEN
gorkaion@14380
  1596
       /************
gorkaion@14380
  1597
        * Shipment
gorkaion@14380
  1598
        */
gorkaion@14380
  1599
        DBMS_OUTPUT.PUT_LINE('Create Shipment - ' || v_Record_ID) ;
gorkaion@14380
  1600
        v_ResultStr:='CreateShipment';
gorkaion@14380
  1601
gorkaion@14380
  1602
        M_Inout_Create(NULL, InOut_ID, v_Record_ID, NULL, 'Y') ; -- Force Delivery
gorkaion@14380
  1603
gorkaion@14380
  1604
        DBMS_OUTPUT.PUT_LINE('  Shipment - ' || InOut_ID) ;
gorkaion@14380
  1605
        IF (InOut_ID='0') THEN
gorkaion@14380
  1606
          RAISE_APPLICATION_ERROR(-20000, '@InOutCreateFailed@');
carlos@0
  1607
        ELSE
gorkaion@14380
  1608
          SELECT documentno
gorkaion@14380
  1609
            INTO v_DocumentNo
gorkaion@14380
  1610
          FROM M_INOUT
gorkaion@14380
  1611
          WHERE M_INOUT_ID = InOut_ID;
gorkaion@14380
  1612
          v_Message:='@InoutDocumentno@ ' || v_DocumentNo || ' @beenCreated@';
gorkaion@14380
  1613
        END IF;
gorkaion@14380
  1614
        IF (v_DocSubTypeSO IN('WI', 'WR')) THEN
gorkaion@14380
  1615
         /************
gorkaion@14380
  1616
          * Invoice
gorkaion@14380
  1617
          */
gorkaion@14380
  1618
          DBMS_OUTPUT.PUT_LINE('Create Invoice - ' || v_Record_ID) ;
gorkaion@14380
  1619
          v_ResultStr:='CreateInvoice';
gorkaion@14380
  1620
          C_Invoice_Create(NULL, Invoice_ID, v_Record_ID) ;
gorkaion@14380
  1621
          DBMS_OUTPUT.PUT_LINE('  Invoice - ' || Invoice_ID) ;
gorkaion@14380
  1622
          IF (Invoice_ID IS NULL OR Invoice_ID='0') THEN
gorkaion@14380
  1623
            RAISE_APPLICATION_ERROR(-20000, '@InvoiceCreateFailed@');
gorkaion@14380
  1624
          ELSE
gorkaion@14380
  1625
            SELECT documentno
gorkaion@14380
  1626
              INTO v_DocumentNo
gorkaion@14380
  1627
            FROM C_INVOICE
gorkaion@14380
  1628
            WHERE C_INVOICE_ID = Invoice_ID;
gorkaion@14380
  1629
            v_Message:=v_Message||' , '||'@InvoiceDocumentno@ ' || v_DocumentNo || ' @invbeenCreated@';
gorkaion@14380
  1630
          END IF;
carlos@0
  1631
        END IF;
carlos@0
  1632
      END IF;
carlos@0
  1633
gorkaion@14380
  1634
     /**
gorkaion@14380
  1635
      * Final Completeness check
gorkaion@14380
  1636
      */
victor@24222
  1637
      SELECT COUNT(*) INTO ToDeliver FROM DUAL
victor@24210
  1638
      WHERE 0 <> ANY (select QtyOrdered - QtyDelivered from c_orderline where c_order_id = v_Record_ID);
victor@24222
  1639
      SELECT COUNT(*) INTO ToInvoice FROM DUAL
victor@24210
  1640
      WHERE 0 <> ANY (select QtyOrdered - QtyInvoiced from c_orderline where c_order_id = v_Record_ID);
gorkaion@14380
  1641
      DBMS_OUTPUT.PUT_LINE('To deliver - ' || ToDeliver) ;
gorkaion@14380
  1642
      DBMS_OUTPUT.PUT_LINE('ToInvoice - ' || ToInvoice) ;
gorkaion@14380
  1643
      DBMS_OUTPUT.PUT_LINE('v_DocSubTypeSO - ' || v_DocSubTypeSO) ;
gorkaion@14380
  1644
      -- Nothing to Deliver + Invoice for (W)illCall(I)nvoice and (W)alkIn(R)eceipt
gorkaion@14380
  1645
      IF (v_DocSubTypeSO IN ('WI', 'WR') AND ToDeliver=0 AND ToInvoice=0) THEN
carlos@0
  1646
        UPDATE C_ORDER
gorkaion@14380
  1647
        SET DocStatus='CO',
gorkaion@14380
  1648
            DocAction='--',
gorkaion@14380
  1649
            IsDelivered='Y',
gorkaion@14380
  1650
            IsInvoiced='Y',
gorkaion@14380
  1651
            Processed='Y',
gorkaion@14380
  1652
            Updated=now(),
gorkaion@14380
  1653
            UpdatedBy=v_User
carlos@0
  1654
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1655
        DBMS_OUTPUT.PUT_LINE('DocAction - ' || v_DocAction) ;
gorkaion@14380
  1656
        IF (v_DocAction='VO') THEN
gorkaion@14380
  1657
          UPDATE C_ORDER  SET DocStatus='VO'  WHERE C_Order_ID=v_Record_ID;
carlos@0
  1658
        END IF;
carlos@0
  1659
      END IF;
gorkaion@14380
  1660
      -- Nothing to Deliver for (W)illCall(P)ickup (Invoice generated independently)
gorkaion@14380
  1661
      IF (v_DocSubTypeSO='WP' AND ToDeliver=0) THEN
gorkaion@14380
  1662
        UPDATE C_ORDER
gorkaion@14380
  1663
        SET DocStatus='CO',
gorkaion@14380
  1664
            DocAction='--',
gorkaion@14380
  1665
            IsDelivered='Y',
gorkaion@14380
  1666
            Processed='Y',
gorkaion@14380
  1667
            Updated=now(),
gorkaion@14380
  1668
            UpdatedBy=v_User
gorkaion@14380
  1669
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1670
        IF (v_DocAction='VO') THEN
gorkaion@14380
  1671
          UPDATE C_ORDER  SET DocStatus='VO'  WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1672
        END IF;
gorkaion@14380
  1673
      END IF;
david@33511
  1674
      
david@33511
  1675
      -- If there is at least one line with different Quantity Ordered than Quantity Delivered, set the IsDelivered flag as N
david@33511
  1676
      -- By default this flag is already N for new Orders, this can happen when the Order has been cloned from another one
david@33511
  1677
      -- that has been already delivered, and then the lines information has changed
david@33511
  1678
      IF (ToDeliver <> 0) THEN
david@33511
  1679
        UPDATE C_ORDER
david@33511
  1680
        SET IsDelivered='N',
david@33511
  1681
            Updated=now(),
david@33511
  1682
            UpdatedBy=v_User
david@33511
  1683
        WHERE C_Order_ID=v_Record_ID;
david@33511
  1684
      END IF;
david@33511
  1685
gorkaion@14380
  1686
      -- We are done with standard sales orders
gorkaion@14546
  1687
      IF (v_DocSubTypeSO = 'RM' OR v_isreturndoctype = 'Y') THEN
harikrishnan@5844
  1688
gorkaion@14380
  1689
        FOR Cur_Order IN( SELECT ol.qtyordered, ol.c_order_discount_id FROM C_order o,C_orderline ol
gorkaion@14380
  1690
            WHERE o.C_Order_ID = v_Record_ID
gorkaion@14380
  1691
              AND ol.C_Order_ID = o.C_Order_ID)
carlos@0
  1692
        LOOP
gorkaion@14380
  1693
          IF (Cur_Order.qtyordered >0 AND Cur_Order.c_order_discount_id IS NULL) THEN 
gorkaion@14380
  1694
            RAISE_APPLICATION_ERROR(-20000, '@ReturnMaterialOrderType@') ;
carlos@0
  1695
          END IF;
carlos@0
  1696
        END LOOP;
carlos@0
  1697
      END IF;
gorkaion@14541
  1698
      IF (v_DocAction IN('CO', 'CL', 'VO') AND v_DocSubTypeSO IN('SO','RM')) THEN
gorkaion@14380
  1699
        UPDATE C_ORDER
gorkaion@14380
  1700
        SET DocStatus='CO',
gorkaion@14380
  1701
            DocAction='--',
gorkaion@14380
  1702
            Processed='Y',
gorkaion@14380
  1703
            Updated=now(),
gorkaion@14380
  1704
            UpdatedBy=v_User
gorkaion@14380
  1705
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1706
      END IF;
gorkaion@14380
  1707
      -- Purchase Orders
gorkaion@14380
  1708
      IF (v_DocAction IN('CO', 'CL', 'VO') AND v_DocSubTypeSO IS NULL) THEN
gorkaion@14380
  1709
        UPDATE C_ORDER
gorkaion@14380
  1710
        SET DocStatus='CO',
gorkaion@14380
  1711
            DocAction='--',
gorkaion@14380
  1712
            Processed='Y',
gorkaion@14380
  1713
            Updated=now(),
gorkaion@14380
  1714
            UpdatedBy=v_User
gorkaion@14380
  1715
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1716
      END IF;
david@18488
  1717
      IF (v_DocAction IN('CO') AND v_DocSubTypeSO IN('OB')) THEN
david@18488
  1718
        UPDATE C_ORDER
david@18488
  1719
        SET DocStatus='UE',
david@18488
  1720
            DocAction='--',
david@18488
  1721
            Processed='Y',
david@18488
  1722
            Updated=now(),
david@18488
  1723
            UpdatedBy=v_User
david@18488
  1724
        WHERE C_Order_ID=v_Record_ID;
david@18488
  1725
      END IF;
gorkaion@14380
  1726
      -- Only create cash entry if docAction is Complete
gorkaion@14380
  1727
      IF (v_DocAction NOT IN('CO')) THEN
gorkaion@14380
  1728
        END_PROCESSING:=TRUE;
gorkaion@14380
  1729
      END IF;
gorkaion@14380
  1730
    END IF;--FINISH_PROCESS
gorkaion@14380
  1731
    IF (NOT FINISH_PROCESS AND NOT END_PROCESSING) THEN
gorkaion@14380
  1732
     /**************************************************************************
gorkaion@14380
  1733
      * Create default Cash entry
carlos@0
  1734
      *************************************************************************/
carlos@0
  1735
      DECLARE
gorkaion@14380
  1736
        v_PaymentRule VARCHAR(60) ;
gorkaion@14380
  1737
        CUR_CB RECORD;
gorkaion@14380
  1738
        v_debtPaymentID varchar2(32);
gorkaion@14380
  1739
        v_totalCash NUMBER;
gorkaion@14380
  1740
        v_CB_Curr varchar2(32);
carlos@0
  1741
      BEGIN
gorkaion@14380
  1742
       /* ALO
gorkaion@14380
  1743
        */
gorkaion@14380
  1744
        UPDATE C_DEBT_PAYMENT  SET IsValid='Y'  WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1745
        SELECT C_ORDER.PAYMENTRULE,
unai@14890
  1746
            (CASE 
unai@14890
  1747
		WHEN (length(C_ORDER.DOCUMENTNO||' - '||C_BPARTNER.NAME||' - '||C_ORDER.GRANDTOTAL) > 200) 
unai@14890
  1748
			THEN substr(C_ORDER.DOCUMENTNO||' - '||C_BPARTNER.NAME||' - '||C_ORDER.GRANDTOTAL,1,197)||'...'
unai@14890
  1749
		ELSE 
unai@14890
  1750
			C_ORDER.DOCUMENTNO||' - '||C_BPARTNER.NAME||' - '||C_ORDER.GRANDTOTAL
unai@14890
  1751
	    END) AS CONCATENATION,
gorkaion@14380
  1752
            C_ORDER.GRANDTOTAL,
gorkaion@14380
  1753
            C_ORDER.M_WAREHOUSE_ID
gorkaion@14380
  1754
          INTO v_PaymentRule,
gorkaion@14380
  1755
            v_DocumentNo,
gorkaion@14380
  1756
            v_GrandTotal,
gorkaion@14380
  1757
            v_M_Warehouse_ID
gorkaion@14380
  1758
        FROM C_ORDER, C_BPARTNER
gorkaion@14380
  1759
        WHERE C_ORDER.C_BPARTNER_ID=C_BPARTNER.C_BPARTNER_ID
gorkaion@14380
  1760
          AND C_ORDER_ID=v_Record_ID;
gorkaion@14380
  1761
        SELECT MAX(NAME)
gorkaion@14380
  1762
          INTO v_WarehouseName
gorkaion@14380
  1763
        FROM M_WAREHOUSE
gorkaion@14380
  1764
        WHERE M_WAREHOUSE_ID=v_M_Warehouse_ID;
gorkaion@14380
  1765
gorkaion@14380
  1766
        --PaymentRule C, WI and WR have already created DP, this won't be inserted in cashline
gorkaion@14380
  1767
        --because it will processed with the invoice.
gorkaion@14380
  1768
        IF (v_PaymentRule='C') AND (v_DocSubTypeSO NOT IN ('WI', 'WR') OR v_DocSubTypeSO IS NULL) THEN
gorkaion@14380
  1769
          IF (v_CashLine_ID IS NULL OR v_CashLine_ID='0') THEN
gorkaion@14380
  1770
            -- Create CashLine
gorkaion@14380
  1771
            -- Find Defaylt CashBook
gorkaion@14380
  1772
            v_ResultStr:='Find C_CashBook Org_ID=' || v_Org_ID;
gorkaion@14380
  1773
            BEGIN
gorkaion@14380
  1774
              -- First active default Book of Org
gorkaion@14380
  1775
              FOR CUR_CB IN
gorkaion@14380
  1776
                 (SELECT cb.C_CashBook_ID, c.ISO_Code, cb.NAME, cb.c_currency_id
gorkaion@14380
  1777
                  FROM C_CASHBOOK cb, C_CURRENCY c
gorkaion@14380
  1778
                  WHERE cb.AD_Org_ID=v_Org_ID
gorkaion@14380
  1779
                    AND cb.C_Currency_ID=c.C_Currency_ID
gorkaion@14380
  1780
                    AND cb.IsActive='Y'
gorkaion@14380
  1781
                  ORDER BY cb.IsDefault DESC
gorkaion@14380
  1782
                 )
gorkaion@14380
  1783
              LOOP
gorkaion@14380
  1784
                IF (v_CashBook_ID IS NULL) THEN
gorkaion@14380
  1785
                  v_CashBook_ID:=CUR_CB.C_CashBook_ID;
gorkaion@14380
  1786
                  v_ISO_Code:=CUR_CB.ISO_Code;
gorkaion@14380
  1787
                  v_CB_Curr:=CUR_CB.C_Currency_ID;
gorkaion@14380
  1788
                ELSIF (CUR_CB.NAME=v_WarehouseName) THEN
gorkaion@14380
  1789
                  v_CashBook_ID:=CUR_CB.C_CashBook_ID;
gorkaion@14380
  1790
                  v_ISO_Code:=CUR_CB.ISO_Code;
gorkaion@14380
  1791
                  v_CB_Curr:=CUR_CB.C_Currency_ID;
gorkaion@14380
  1792
                END IF;
gorkaion@14380
  1793
              END LOOP;
gorkaion@14380
  1794
            END;
gorkaion@14380
  1795
            IF (v_CashBook_ID IS NULL) THEN
gorkaion@14380
  1796
              RAISE_APPLICATION_ERROR(-20000, '@CashBookPRSCnotfoundOrg@' || v_Org_Name) ;
gorkaion@14380
  1797
            END IF;
gorkaion@14380
  1798
            DBMS_OUTPUT.PUT_LINE('CashBook_ID=' || v_CashBook_ID) ;
gorkaion@14380
  1799
            -- Find/Create Cash Journal
gorkaion@14380
  1800
            v_ResultStr:='Find C_Cash for ' || v_Date;
gorkaion@14380
  1801
            DECLARE
gorkaion@14380
  1802
              Cur_CashId RECORD;
gorkaion@14380
  1803
            BEGIN
gorkaion@14380
  1804
              FOR Cur_CashId IN
gorkaion@14380
  1805
                 (SELECT C_Cash_ID AS Cash_ID
gorkaion@14380
  1806
                  FROM C_CASH
gorkaion@14380
  1807
                  WHERE C_CashBook_ID=v_CashBook_ID
gorkaion@14380
  1808
                    AND TRUNC(StatementDate)=v_Date
gorkaion@14380
  1809
                    AND Processed='N'
gorkaion@14380
  1810
                 )
gorkaion@14380
  1811
              LOOP
gorkaion@14380
  1812
                v_Cash_ID:=Cur_CashId.Cash_ID;
gorkaion@14380
  1813
                EXIT;
gorkaion@14380
  1814
              END LOOP;
gorkaion@14380
  1815
            EXCEPTION
gorkaion@14380
  1816
              WHEN NO_DATA_FOUND THEN
gorkaion@14380
  1817
                NULL;
gorkaion@14380
  1818
            END;
gorkaion@14380
  1819
gorkaion@14380
  1820
            IF (v_Cash_ID IS NULL) THEN
gorkaion@14380
  1821
              v_ResultStr:='Create C_Cash';
gorkaion@14380
  1822
              Ad_Sequence_Next('C_Cash', v_Org_ID, v_Cash_ID) ;
gorkaion@14380
  1823
              INSERT
gorkaion@14380
  1824
              INTO C_CASH
gorkaion@14380
  1825
                (
gorkaion@14380
  1826
                  C_Cash_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@14380
  1827
                  Created, CreatedBy, Updated, UpdatedBy,
gorkaion@14380
  1828
                  C_CashBook_ID, NAME, StatementDate, DateAcct,
gorkaion@14380
  1829
                  BeginningBalance, EndingBalance, StatementDifference, Processing,
gorkaion@14380
  1830
                  Processed, Posted
gorkaion@14380
  1831
                )
gorkaion@14380
  1832
              VALUES
gorkaion@14380
  1833
                (
gorkaion@14380
  1834
                  v_Cash_ID, v_Client_ID, v_Org_ID, 'Y',
gorkaion@14380
  1835
                  now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@14380
  1836
                  v_CashBook_ID, TO_CHAR(v_Date, 'YYYY-MM-DD') || ' ' || v_ISO_Code, v_Date, v_Date,
gorkaion@14380
  1837
                  0, 0, 0, 'N',
gorkaion@14380
  1838
                  'N', 'N'
gorkaion@14380
  1839
                )
gorkaion@14380
  1840
              ;
gorkaion@14380
  1841
            END IF;
gorkaion@14380
  1842
           /*
gorkaion@14380
  1843
            Create a debt payment for paymentrule=C
gorkaion@14380
  1844
            Note: for WI and WR we have already created an invoice and its DP, we only have to link it
gorkaion@14380
  1845
            */
gorkaion@14380
  1846
            SELECT COALESCE(SUM(C_Currency_Round(C_Currency_Convert((Amount + WriteOffAmt), C_Currency_ID, v_CB_Curr, v_Date, NULL, v_Client_ID, v_Org_ID), v_c_Currency_ID, NULL)), 0)
gorkaion@14380
  1847
              INTO v_totalCash
gorkaion@14380
  1848
            FROM C_DEBT_PAYMENT_V dp
gorkaion@14380
  1849
            WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1850
gorkaion@14380
  1851
            Ad_Sequence_Next('C_Debt_Payment', v_Record_ID, v_debtPaymentID) ;
gorkaion@14380
  1852
            INSERT INTO C_DEBT_PAYMENT
gorkaion@14380
  1853
               (C_DEBT_PAYMENT_ID, AD_CLIENT_ID, AD_ORG_ID, ISACTIVE,
gorkaion@14380
  1854
                CREATED, CREATEDBY, UPDATED, UPDATEDBY,
gorkaion@14380
  1855
                ISRECEIPT, C_SETTLEMENT_CANCEL_ID, C_SETTLEMENT_GENERATE_ID, DESCRIPTION,
gorkaion@14380
  1856
                C_ORDER_ID, C_BPARTNER_ID, C_CURRENCY_ID, C_CASHLINE_ID,
gorkaion@14380
  1857
                C_BANKACCOUNT_ID, C_CASHBOOK_ID, PAYMENTRULE, ISPAID,
gorkaion@14380
  1858
                AMOUNT, WRITEOFFAMT, DATEPLANNED, ISMANUAL,
gorkaion@14380
  1859
                ISVALID, C_BANKSTATEMENTLINE_ID, CHANGESETTLEMENTCANCEL, CANCEL_PROCESSED,
gorkaion@14380
  1860
                GENERATE_PROCESSED, c_project_id,IsAutomaticGenerated, STATUS_INITIAL)
gorkaion@14380
  1861
            VALUES
gorkaion@14380
  1862
               (v_debtPaymentID, v_Client_ID, v_Org_ID, 'Y',
gorkaion@14380
  1863
                now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@14380
  1864
                v_isSoTrx, NULL, NULL, '',
gorkaion@14380
  1865
                v_Record_ID, v_c_Bpartner_Id, v_c_currency_id, null,
gorkaion@14380
  1866
                NULL, v_CashBook_ID, 'C', 'N',
gorkaion@14380
  1867
                (v_GrandTotal-v_totalCash), 0, v_Date, 'N',
gorkaion@14380
  1868
                'Y', NULL, 'N', 'N',
gorkaion@14380
  1869
                'N', v_C_PROJECT_ID,'Y', 'DE');
gorkaion@14380
  1870
gorkaion@14380
  1871
            DBMS_OUTPUT.PUT_LINE('  Cash_ID=' || v_Cash_ID) ;
gorkaion@14380
  1872
            -- Create CashJournal Line in invoice currency
gorkaion@14380
  1873
            v_ResultStr:='Create C_CashLine';
gorkaion@14380
  1874
            Ad_Sequence_Next('C_CashLine', v_Org_ID, v_CashLine_ID) ;
gorkaion@14380
  1875
gorkaion@14380
  1876
            SELECT COALESCE(MAX(Line), 0) +10
gorkaion@14380
  1877
              INTO v_Line
gorkaion@14380
  1878
            FROM C_CASHLINE
gorkaion@14380
  1879
            WHERE C_Cash_ID=v_Cash_ID;
gorkaion@14380
  1880
            --
gorkaion@14380
  1881
            INSERT
gorkaion@14380
  1882
            INTO C_CASHLINE
gorkaion@14380
  1883
              (
gorkaion@14380
  1884
                C_CashLine_ID, AD_Client_ID, AD_Org_ID, IsActive,
gorkaion@14380
  1885
                Created, CreatedBy, Updated, UpdatedBy,
gorkaion@14380
  1886
                C_Cash_ID, C_Debt_Payment_ID, Line, Description,
gorkaion@14380
  1887
                Amount, CashType, DiscountAmt, WriteOffAmt,
gorkaion@14380
  1888
                IsGenerated
gorkaion@14380
  1889
              )
gorkaion@14380
  1890
            VALUES
gorkaion@14380
  1891
              (
gorkaion@14380
  1892
                v_CashLine_ID, v_Client_ID, v_Org_ID, 'Y',
gorkaion@14380
  1893
                now(), v_UpdatedBy, now(), v_UpdatedBy,
gorkaion@14380
  1894
                v_Cash_ID, v_debtPaymentID, v_Line, v_DocumentNo,
gorkaion@14380
  1895
                (v_GrandTotal-v_totalCash) * (CASE WHEN v_isSoTrx='N' THEN -1 ELSE 1 END), 'P', 0, 0,
gorkaion@14380
  1896
                'Y'
gorkaion@14380
  1897
              )
gorkaion@14380
  1898
            ;
gorkaion@14380
  1899
            DBMS_OUTPUT.PUT_LINE('  CashLine_ID=' || v_CashLine_ID) ;
gorkaion@14380
  1900
gorkaion@14380
  1901
          END IF; -- CashLine_ID IS NULL OR CashLine_ID = '0'
gorkaion@14380
  1902
        END IF; -- v_PaymentRule = 'C'
carlos@0
  1903
      END;
gorkaion@14380
  1904
    END IF;--FINISH_PROCESS
gorkaion@14380
  1905
    IF (NOT FINISH_PROCESS) THEN
gorkaion@14380
  1906
      -- End Processing --------------------------------------------------------
gorkaion@14380
  1907
      --<<END_PROCESSING>>
gorkaion@14380
  1908
      -- Cloase Order
gorkaion@14380
  1909
      IF (v_DocAction='CL') THEN
gorkaion@14380
  1910
        UPDATE C_ORDER
gorkaion@14380
  1911
        SET DocStatus='CL',
gorkaion@14380
  1912
            DocAction='--',
gorkaion@14380
  1913
            Processed='Y'
gorkaion@14380
  1914
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1915
      END IF;
gorkaion@14380
  1916
    END IF;--FINISH_PROCESS
carlos@0
  1917
alvaro@31672
  1918
    -- Round and Adjust taxes when 'CO' and Recalculate amounts and taxes when 'RE'
alvaro@31672
  1919
    IF (v_isTaxIncluded = 'Y' AND v_DocAction IN ('CO', 'RE')) THEN
alvaro@31672
  1920
      C_ORDERTAX_ADJUSTMENT(v_Record_ID, v_stdPrecision, v_DocAction);
alvaro@31672
  1921
    END IF;
alvaro@31672
  1922
gorkaion@14380
  1923
    --C_Order_Post - Finish_Process Extension Point
gorkaion@14380
  1924
    SELECT count(*) INTO v_count
gorkaion@14380
  1925
    FROM DUAL
gorkaion@14380
  1926
    where exists (select 1 from ad_ep_procedures where ad_extension_points_id = 'CB68FC0E8A4547D9943C785761977E77');
gorkaion@14380
  1927
    IF (v_count=1) THEN
gorkaion@14380
  1928
      DECLARE
gorkaion@14380
  1929
        v_ep_instance VARCHAR2(32);
gorkaion@14380
  1930
        v_extension_point_id VARCHAR2(32) := 'CB68FC0E8A4547D9943C785761977E77';
gorkaion@14380
  1931
      BEGIN
gorkaion@14380
  1932
        v_ep_instance := get_uuid();
gorkaion@14380
  1933
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Record_ID',
gorkaion@14380
  1934
          v_record_id, NULL, NULL, NULL, NULL, NULL, NULL);
gorkaion@14380
  1935
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'DocAction',
gorkaion@14380
  1936
          v_DocAction, NULL, NULL, NULL, NULL, NULL, NULL);
gorkaion@14380
  1937
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'User',
gorkaion@14380
  1938
          v_User, NULL, NULL, NULL, NULL, NULL, NULL);
gorkaion@14380
  1939
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Message',
gorkaion@14380
  1940
          NULL, NULL, NULL, NULL, NULL, NULL, v_Message);
gorkaion@14380
  1941
        AD_EP_INSTANCE_PARA_INSERT(v_ep_instance, v_extension_point_id, 'Result',
gorkaion@14380
  1942
          NULL, NULL, v_result, NULL, NULL, NULL, NULL);
gorkaion@14380
  1943
        AD_EXTENSION_POINT_HANDLER(v_ep_instance, v_extension_point_id);
gorkaion@14380
  1944
        SELECT p_number INTO v_Result
gorkaion@14380
  1945
        FROM ad_ep_instance_para
gorkaion@14380
  1946
        WHERE ad_ep_instance_id = v_ep_instance
gorkaion@14380
  1947
          AND parametername LIKE 'Result';
gorkaion@14380
  1948
        SELECT p_text INTO v_Message
gorkaion@14380
  1949
        FROM ad_ep_instance_para
gorkaion@14380
  1950
        WHERE ad_ep_instance_id = v_ep_instance
gorkaion@14380
  1951
          AND parametername LIKE 'Message';
carlos@0
  1952
gorkaion@14380
  1953
        DELETE FROM ad_ep_instance_para
gorkaion@14380
  1954
        WHERE ad_ep_instance_id = v_ep_instance;
gorkaion@14380
  1955
      END;
gorkaion@14380
  1956
    END IF;
carlos@0
  1957
gorkaion@14380
  1958
    IF (NOT FINISH_PROCESS) THEN
gorkaion@14380
  1959
      IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@14380
  1960
        v_ResultStr:='UnLockingOrder';
gorkaion@14380
  1961
        UPDATE C_ORDER
gorkaion@14380
  1962
        SET Processing='N',
gorkaion@14380
  1963
            Updated=now(),
gorkaion@14380
  1964
            UpdatedBy=v_User
gorkaion@14380
  1965
        WHERE C_Order_ID=v_Record_ID;
gorkaion@14380
  1966
        COMMIT;
carlos@0
  1967
      END IF;
gorkaion@14380
  1968
    END IF;--FINISH_PROCESS
carlos@0
  1969
gorkaion@14380
  1970
    --<<FINISH_PROCESS>>
gorkaion@14380
  1971
    IF (p_PInstance_ID IS NOT NULL) THEN
gorkaion@14380
  1972
      --  Update AD_PInstance
gorkaion@14380
  1973
      DBMS_OUTPUT.PUT_LINE('Updating PInstance - Finished - ' || v_Message) ;
gorkaion@14380
  1974
      AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'N', v_Result, v_Message) ;
gorkaion@14380
  1975
    END IF;
gorkaion@14380
  1976
    RETURN;
gorkaion@14380
  1977
  END; --BODY
carlos@0
  1978
EXCEPTION
carlos@0
  1979
WHEN OTHERS THEN
carlos@0
  1980
  DBMS_OUTPUT.PUT_LINE(v_ResultStr) ;
carlos@0
  1981
  v_ResultStr:= '@ERROR=' || SQLERRM;
carlos@0
  1982
  IF(p_PInstance_ID IS NOT NULL) THEN
carlos@0
  1983
    ROLLBACK;
carlos@0
  1984
    --Inserted by Carlos Romero 062706
carlos@0
  1985
    UPDATE C_ORDER  SET Processing='N'  WHERE C_Order_ID=v_Record_ID;
carlos@0
  1986
    DBMS_OUTPUT.PUT_LINE(v_ResultStr) ;
antonio@735
  1987
    AD_UPDATE_PINSTANCE(p_PInstance_ID, NULL, 'N', 0, v_ResultStr) ;
carlos@0
  1988
  ELSE
carlos@0
  1989
    RAISE;
carlos@0
  1990
  END IF;
carlos@0
  1991
  RETURN;
antonio@735
  1992
END C_ORDER_POST1
gorkaion@239
  1993
]]></body>
carlos@0
  1994
    </function>
adrian@94
  1995
  </database>