}   //  generatePaySelect

        /// <summary>
        /// Create Check
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="line"></param>
        /// <param name="_list"></param>
        private void CreateCheck(Ctx ctx, MPaySelectionLine line, List <MPaySelectionCheck> _list)
        {
            string _PaymentRule = "S";

            if (_PaymentRule != null && _PaymentRule.Equals(X_C_Order.PAYMENTRULE_DirectDebit))
            {
                _PaymentRule = null;
            }
            ////	Try to find one
            for (int i = 0; i < _list.Count; i++)
            {
                MPaySelectionCheck check = (MPaySelectionCheck)_list[i];
                //	Add to existing
                if (check.GetC_BPartner_ID() == line.GetInvoice().GetC_BPartner_ID())
                {
                    check.AddLine(line);
                    if (!check.Save())
                    {
                        throw new Exception("Cannot save MPaySelectionCheck");
                    }
                    line.SetC_PaySelectionCheck_ID(check.GetC_PaySelectionCheck_ID());
                    line.SetProcessed(true);
                    if (!line.Save())
                    {
                        throw new Exception("Cannot save MPaySelectionLine");
                    }
                    return;
                }
            }
            ////	Create new
            String PaymentRule = line.GetPaymentRule();

            if (_PaymentRule != null && _PaymentRule != " ")
            {
                if (!X_C_Order.PAYMENTRULE_DirectDebit.Equals(PaymentRule))
                {
                    PaymentRule = _PaymentRule;
                }
            }
            MPaySelectionCheck check1 = new MPaySelectionCheck(line, PaymentRule);

            if (!check1.IsValid())
            {
                int       C_BPartner_ID = check1.GetC_BPartner_ID();
                MBPartner bp            = MBPartner.Get(ctx, C_BPartner_ID);
                String    msg           = "@NotFound@ @C_BP_BankAccount@: " + bp.GetName();
                throw new Exception(msg);
            }
            if (!check1.Save())
            {
                throw new Exception("Cannot save MPaySelectionCheck");
            }
            line.SetC_PaySelectionCheck_ID(check1.GetC_PaySelectionCheck_ID());
            line.SetProcessed(true);
            if (!line.Save())
            {
                throw new Exception("Cannot save MPaySelectionLine");
            }
            _list.Add(check1);
        }
Exemple #2
0
 /// <summary>
 /// Check BP
 /// </summary>
 /// <param name="bp">bp bp</param>
 private void CheckBP(MBPartner bp)
 {
     AddLog(0, null, null, bp.GetName() + ":");
     //	See also VMerge.postMerge
     CheckPayments(bp);
     CheckInvoices(bp);
     //
     bp.SetTotalOpenBalance();
     bp.SetActualLifeTimeValue();
     bp.Save();
     //
     //	if (bp.getSO_CreditUsed().signum() != 0)
     AddLog(0, null, bp.GetSO_CreditUsed(), Msg.GetElement(GetCtx(), "SO_CreditUsed"));
     AddLog(0, null, bp.GetTotalOpenBalance(), Msg.GetElement(GetCtx(), "TotalOpenBalance"));
     AddLog(0, null, bp.GetActualLifeTimeValue(), Msg.GetElement(GetCtx(), "ActualLifeTimeValue"));
     //
     Commit();
 }       //	checkBP
        /// <summary>
        /// Generate Contract Invoice
        /// </summary>
        /// <param name="contSchedule"></param>
        private void GenerateInvoice(VAdvantage.Model.X_C_ContractSchedule contSchedule)
        {
            if (contSchedule.IsActive())
            {
                int res = 0;
                sql.Clear();
                sql.Append(MRole.GetDefault(GetCtx()).AddAccessSQL("SELECT MIN(C_DOCTYPE_ID) FROM C_DocType WHERE DOCBASETYPE='ARI' AND ISACTIVE ='Y'", "C_DocType", true, true));
                int C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));

                // sql = "select noofdays from c_frequency where c_frequency_id = " + cont.GetC_Frequency_ID();
                //  Decimal? days = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null));
                Decimal?price = null;

                if (!cont.IsCancel())
                {
                    price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());
                }
                else
                {
                    sql.Clear();
                    sql.Append("UPDATE C_Contract SET RenewalType = NULL WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                    int res2 = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));

                    if (contSchedule.GetEndDate() <= cont.GetCancellationDate())
                    {
                        price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());
                    }
                    else
                    {
                        sql.Clear();
                        sql.Append("SELECT MAX(C_ContractSchedule_ID) FROM C_ContractSchedule WHERE NVL(C_INVOICE_ID,0) > 0 AND C_Contract_ID = " + cont.GetC_Contract_ID());
                        int c_contractschedule_id = Util.GetValueOfInt(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));
                        if (c_contractschedule_id != 0)
                        {
                            string date = cont.GetCancellationDate().Value.ToString("dd-MMM-yyyy");

                            sql.Clear();
                            sql.Append("SELECT DaysBetween('" + date + "', EndDate) FROM C_ContractSchedule WHERE C_ContractSchedule_ID = " + c_contractschedule_id);
                            Decimal?diffDays = Util.GetValueOfDecimal(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));

                            price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());

                            sql.Clear();
                            sql.Append("UPDATE C_ContractSchedule SET IsActive = 'N' WHERE EndDate > '" + date + "' AND C_Contract_ID = " + cont.GetC_Contract_ID());
                            res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                        }
                        else
                        {
                            sql.Clear();
                            sql.Append("SELECT DaysBetween(CancellationDate, StartDate) FROM C_Contract WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                            Decimal?diffDays = Util.GetValueOfDecimal(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));

                            price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());

                            if (diffDays > 0)
                            {
                                sql.Clear();
                                sql.Append("UPDATE C_ContractSchedule SET IsActive = 'N' WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                                res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                            }
                            else
                            {
                                sql.Clear();
                                sql.Append("UPDATE C_ContractSchedule SET IsActive = 'N' WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                                res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                            }
                        }
                    }
                }

                price = Decimal.Round(price.Value, 2, MidpointRounding.AwayFromZero);

                inv = new VAdvantage.Model.MInvoice(GetCtx(), 0, Get_TrxName());
                inv.SetAD_Client_ID(cont.GetAD_Client_ID());
                inv.SetAD_Org_ID(cont.GetAD_Org_ID());
                inv.SetC_BPartner_ID(cont.GetC_BPartner_ID());
                if (Util.GetValueOfInt(cont.GetC_Order_ID()) != 0)
                {
                    inv.SetC_Order_ID(cont.GetC_Order_ID());
                }
                // JID_0872: System has To pick the Payment Method defined with the Business Partner against whom the Invoice is getting generated.
                if (Env.IsModuleInstalled("VA009_"))
                {
                    if (bp.GetVA009_PaymentMethod_ID() > 0)
                    {
                        inv.SetVA009_PaymentMethod_ID(bp.GetVA009_PaymentMethod_ID());
                    }
                    else
                    {
                        throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_PaymentMethodNotDefined") + " : " + bp.GetName());
                    }
                }
                inv.SetC_DocType_ID(C_DocType_ID);
                inv.SetC_DocTypeTarget_ID(C_DocType_ID);
                inv.SetC_BPartner_Location_ID(cont.GetBill_Location_ID());
                inv.SetC_Currency_ID(cont.GetC_Currency_ID());
                inv.SetC_PaymentTerm_ID(cont.GetC_PaymentTerm_ID());
                inv.SetC_Campaign_ID(cont.GetC_Campaign_ID());
                inv.SetIsSOTrx(true);
                inv.SetM_PriceList_ID(cont.GetM_PriceList_ID());
                inv.SetSalesRep_ID(cont.GetSalesRep_ID());
                inv.SetC_Contract_ID(cont.GetC_Contract_ID());
                if (!inv.Save())
                {
                    //Neha----If Invoice not saved then will show the exception---11 Sep,2018
                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                    if (pp != null)
                    {
                        throw new ArgumentException("Cannot save Invoice. " + pp.GetName());
                    }
                    throw new ArgumentException("Cannot save Invoice");
                }

                else
                {
                    VAdvantage.Model.MInvoiceLine invLine = new VAdvantage.Model.MInvoiceLine(GetCtx(), 0, Get_TrxName());
                    invLine.SetAD_Client_ID(inv.GetAD_Client_ID());
                    invLine.SetAD_Org_ID(inv.GetAD_Org_ID());
                    invLine.SetC_Campaign_ID(inv.GetC_Campaign_ID());
                    invLine.SetC_Invoice_ID(inv.GetC_Invoice_ID());
                    invLine.SetC_UOM_ID(cont.GetC_UOM_ID());
                    invLine.SetM_Product_ID(cont.GetM_Product_ID());
                    // Added by Vivek on 21/11/2017 asigned by Pradeep
                    invLine.SetM_AttributeSetInstance_ID(cont.GetM_AttributeSetInstance_ID());
                    if (Util.GetValueOfInt(cont.GetC_OrderLine_ID()) != 0)
                    {
                        invLine.SetC_OrderLine_ID(cont.GetC_OrderLine_ID());
                    }
                    invLine.SetC_Tax_ID(cont.GetC_Tax_ID());
                    invLine.SetQty(cont.GetQtyEntered());
                    invLine.SetQtyEntered(cont.GetQtyEntered());
                    // invLine.SetQtyInvoiced(1);
                    // invLine.SetPrice(price.Value);
                    invLine.SetPriceActual(cont.GetPriceEntered());
                    invLine.SetPriceEntered(cont.GetPriceEntered());
                    //  invLine.SetPriceLimit(price);
                    invLine.SetPriceList(cont.GetPriceEntered());
                    if (!invLine.Save())
                    {
                        //Neha----If Invoice Line not saved then will show the exception---11 Sep,2018
                        ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                        if (pp != null)
                        {
                            throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName());
                        }
                        throw new ArgumentException("Cannot save Invoice Line");
                    }
                }

                string comp = inv.CompleteIt();
                //Neha---If Invoice Completed then Set Document Action, Document Status and Contract on Invoice Header---11 Sep,2018
                if (comp == "CO")
                {
                    inv.SetDocAction("CL");
                    inv.SetDocStatus("CO");
                    //Neha---Set C_Contract_ID on C_invoice table using MClass object--11 Sep,2018
                    inv.SetC_Contract_ID(cont.GetC_Contract_ID());
                    if (!inv.Save())
                    {
                        //Neha----If Invoice not saved then will show the exception---11 Sep,2018
                        ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                        if (pp != null)
                        {
                            throw new ArgumentException("Cannot save Invoice. " + pp.GetName());
                        }
                        throw new ArgumentException("Cannot save Invoice");
                    }
                }
                else
                {
                    //Neha----If Invoice not completed then will show the exception---11 Sep,2018
                    if (inv.GetProcessMsg() != null)
                    {
                        throw new ArgumentException("Cannot complete the Invoice. " + inv.GetProcessMsg());
                    }
                    throw new ArgumentException("Cannot complete the Invoice");
                }

                #region Commented Code
                //Neha---Set C_Contract_ID on C_invoice table using MClass object--11 Sep,2018

                //sql = "UPDATE c_invoice SET C_Contract_ID = " + cont.GetC_Contract_ID() + " WHERE c_invoice_id = " + inv.GetC_Invoice_ID();
                //res = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, null));

                //Neha---taxAmt not used in this class----11 Sep,2018

                //sql = "SELECT SUM(taxamt) FROM c_invoicetax WHERE c_invoice_id = " + inv.GetC_Invoice_ID();
                //Decimal? taxAmt = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null));
                # endregion
                sql.Clear();
                sql.Append("UPDATE C_ContractSchedule SET C_Invoice_ID = " + inv.GetC_Invoice_ID() + ", Processed = 'Y' WHERE C_ContractSchedule_ID = " + contSchedule.GetC_ContractSchedule_ID());
                res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                //Neha---Append Document No. in sb----12 Sep,2018
                sb.Append(inv.GetDocumentNo() + ", ");
                //_count++;
            }
Exemple #4
0
        /// <summary>
        /// Generate Invoices
        /// </summary>
        /// <param name="idr">pstmt order query</param>
        /// <returns>info</returns>
        //private String Generate(IDataReader idr)
        private String Generate(DataTable dt)
        {
            //JID_1139 Avoided the duplicate charge line created Invoice(customer)
            bool isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y");

            foreach (DataRow dr in dt.Rows)
            {
                MOrder order = new MOrder(GetCtx(), dr, Get_TrxName());

                // Credit Limit check
                MBPartner bp = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                if (bp.GetCreditStatusSettingOn() == "CH")
                {
                    decimal creditLimit = bp.GetSO_CreditLimit();
                    string  creditVal   = bp.GetCreditValidation();
                    if (creditLimit != 0)
                    {
                        decimal creditAvlb = creditLimit - bp.GetSO_CreditUsed();
                        if (creditAvlb <= 0)
                        {
                            if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                            {
                                AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName());
                                continue;
                            }
                            else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                            {
                                if (_msg != null)
                                {
                                    _msg.Clear();
                                }
                                _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                                //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                            }
                        }
                    }
                }
                // JID_0161 // change here now will check credit settings on field only on Business Partner Header // Lokesh Chauhan 15 July 2019
                else if (bp.GetCreditStatusSettingOn() == X_C_BPartner.CREDITSTATUSSETTINGON_CustomerLocation)
                {
                    MBPartnerLocation bpl = new MBPartnerLocation(GetCtx(), order.GetC_BPartner_Location_ID(), null);
                    //MBPartner bpartner = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                    //if (bpl.GetCreditStatusSettingOn() == "CL")
                    //{
                    decimal creditLimit = bpl.GetSO_CreditLimit();
                    string  creditVal   = bpl.GetCreditValidation();
                    if (creditLimit != 0)
                    {
                        decimal creditAvlb = creditLimit - bpl.GetSO_CreditUsed();
                        if (creditAvlb <= 0)
                        {
                            if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                            {
                                AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName() + " " + bpl.GetName());
                                continue;
                            }
                            else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                            {
                                if (_msg != null)
                                {
                                    _msg.Clear();
                                }
                                _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                                //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                            }
                        }
                    }
                    //}
                }
                // Credit Limit End

                //	New Invoice Location
                // JID_1237 : While creating invoice need to consolidate order on the basis of Org, Payment Term, BP Location (Bill to Location) and Pricelist.
                if (!_ConsolidateDocument ||
                    (_invoice != null &&
                     (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() ||
                      _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID() ||
                      _invoice.GetM_PriceList_ID() != order.GetM_PriceList_ID() ||
                      _invoice.GetAD_Org_ID() != order.GetAD_Org_ID() ||
                      ((_invoice.GetC_ConversionType_ID() != 0 ? _invoice.GetC_ConversionType_ID() : defaultConversionType)
                       != (order.GetC_ConversionType_ID() != 0 ? order.GetC_ConversionType_ID() : defaultConversionType))
                     )))
                {
                    CompleteInvoice();
                }
                bool completeOrder = MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule());

                //	Schedule After Delivery
                bool doInvoice = false;
                if (MOrder.INVOICERULE_CustomerScheduleAfterDelivery.Equals(order.GetInvoiceRule()))
                {
                    _bp = new MBPartner(GetCtx(), order.GetBill_BPartner_ID(), null);
                    if (_bp.GetC_InvoiceSchedule_ID() == 0)
                    {
                        log.Warning("BPartner has no Schedule - set to After Delivery");
                        order.SetInvoiceRule(MOrder.INVOICERULE_AfterDelivery);
                        order.Save();
                    }
                    else
                    {
                        MInvoiceSchedule ins = MInvoiceSchedule.Get(GetCtx(), _bp.GetC_InvoiceSchedule_ID(), Get_TrxName());
                        if (ins.CanInvoice(order.GetDateOrdered(), order.GetGrandTotal()))
                        {
                            doInvoice = true;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }       //	Schedule

                //	After Delivery
                if (doInvoice || MOrder.INVOICERULE_AfterDelivery.Equals(order.GetInvoiceRule()))
                {
                    MInOut       shipment      = null;
                    MInOutLine[] shipmentLines = order.GetShipmentLines();
                    MOrderLine[] oLines        = order.GetLines(true, null);
                    for (int i = 0; i < shipmentLines.Length; i++)
                    {
                        MInOutLine shipLine = shipmentLines[i];
                        if (shipLine.IsInvoiced())
                        {
                            continue;
                        }
                        if (shipment == null ||
                            shipment.GetM_InOut_ID() != shipLine.GetM_InOut_ID())
                        {
                            shipment = new MInOut(GetCtx(), shipLine.GetM_InOut_ID(), Get_TrxName());
                        }
                        if (!shipment.IsComplete() ||           //	ignore incomplete or reversals
                            shipment.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed))
                        {
                            continue;
                        }
                        //JID_1139 Avoided the duplicate charge records
                        if (shipLine.GetM_Product_ID() > 0 || isAllownonItem)
                        {
                            CreateLine(order, shipment, shipLine);
                        }
                    }//	shipment lines

                    //JID_1139 Avoided the duplicate charge records
                    if (!isAllownonItem)
                    {
                        for (int i = 0; i < oLines.Length; i++)
                        {
                            MOrderLine oLine = oLines[i];
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                                log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine);
                                Decimal qtyEntered = toInvoice;
                                //	Correct UOM for QtyEntered
                                if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                                {
                                    qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                                  toInvoice, oLine.GetQtyEntered()),
                                                                              oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                                }
                                //JID_1139_1 avoided the charge line with 0 qty inserted
                                if (oLine.IsContract() == false && oLine.GetQtyOrdered() > oLine.GetQtyInvoiced())
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }
                    }
                }
                //	After Order Delivered, Immediate
                else
                {
                    MOrderLine[] oLines = order.GetLines(true, null);
                    for (int i = 0; i < oLines.Length; i++)
                    {
                        MOrderLine oLine     = oLines[i];
                        Decimal    toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                        if (toInvoice.CompareTo(Env.ZERO) == 0 && oLine.GetM_Product_ID() != 0)
                        {
                            continue;
                        }
                        //
                        bool fullyDelivered = oLine.GetQtyOrdered().CompareTo(oLine.GetQtyDelivered()) == 0;
                        //JID_1136: While creating the Invoices against the charge system should not check the Ordered qty= Delivered qty. need to check this only in case of products
                        if (completeOrder && oLine.GetC_Charge_ID() > 0)
                        {
                            fullyDelivered = true;
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                log.Fine("After Order Delivery - ToInvoice=" + toInvoice + " - " + oLine);
                                Decimal qtyEntered = toInvoice;
                                //	Correct UOM for QtyEntered
                                if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                                {
                                    qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                                  toInvoice, oLine.GetQtyEntered()),
                                                                              oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                                }
                                //
                                if (oLine.IsContract() == false && !isAllownonItem)
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }

                        //	Complete Order
                        if (completeOrder && !fullyDelivered)
                        {
                            log.Fine("Failed CompleteOrder - " + oLine);
                            completeOrder = false;
                            break;
                        }
                        //	Immediate
                        else if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule()))
                        {
                            log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine);
                            Decimal qtyEntered = toInvoice;
                            //	Correct UOM for QtyEntered
                            if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                            {
                                qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                              toInvoice, oLine.GetQtyEntered()),
                                                                          oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                            }
                            //
                            if (oLine.IsContract() == false)
                            {
                                CreateLine(order, oLine, toInvoice, qtyEntered);
                                log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                            }
                        }
                        else
                        {
                            log.Fine("Failed: " + order.GetInvoiceRule()
                                     + " - ToInvoice=" + toInvoice + " - " + oLine);
                        }
                    }   //	for all order lines
                    if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule()))
                    {
                        _line += 1000;
                    }
                }

                //	Complete Order successful
                if (completeOrder && MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule()))
                {
                    MInOut[] shipments = order.GetShipments(true);
                    for (int i = 0; i < shipments.Length; i++)
                    {
                        MInOut ship = shipments[i];
                        if (!ship.IsComplete() ||       //	ignore incomplete or reversals
                            ship.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed))
                        {
                            continue;
                        }
                        MInOutLine[] shipLines = ship.GetLines(false);
                        for (int j = 0; j < shipLines.Length; j++)
                        {
                            MInOutLine shipLine = shipLines[j];
                            if (!order.IsOrderLine(shipLine.GetC_OrderLine_ID()))
                            {
                                continue;
                            }
                            if (!shipLine.IsInvoiced())
                            {
                                CreateLine(order, ship, shipLine);
                            }
                        } //	lines
                        _line += 1000;
                    }     //	all shipments
                }         //	complete Order
            }             //	for all orders

            CompleteInvoice();
            return("@Created@ = " + _created);
        }
        }       //	doIt

        /// <summary>
        /// Process Expense Line
        /// </summary>
        /// <param name="te">header</param>
        /// <param name="tel">line</param>
        /// <param name="bp">bp</param>
        private void ProcessLine(MTimeExpense te, MTimeExpenseLine tel, MBPartner bp)
        {
            if (_order == null)
            {
                log.Info("New Order for " + bp + ", Project=" + tel.GetC_Project_ID());
                _order = new MOrder(GetCtx(), 0, Get_TrxName());
                _order.SetAD_Org_ID(tel.GetAD_Org_ID());
                _order.SetC_DocTypeTarget_ID(MOrder.DocSubTypeSO_Standard);
                //
                _order.SetBPartner(bp);
                if (_order.GetC_BPartner_Location_ID() == 0)
                {
                    log.Log(Level.SEVERE, "No BP Location: " + bp);
                    AddLog(0, te.GetDateReport(),
                           null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName());
                    _order = null;
                    return;
                }
                _order.SetM_Warehouse_ID(te.GetM_Warehouse_ID());

                ////Added By Arpit asked by Surya Sir..................29-12-2015
                //_order.SetSalesRep_ID(GetCtx().GetAD_User_ID());
                //End
                if (tel.GetC_Activity_ID() != 0)
                {
                    _order.SetC_Activity_ID(tel.GetC_Activity_ID());
                }
                if (tel.GetC_Campaign_ID() != 0)
                {
                    _order.SetC_Campaign_ID(tel.GetC_Campaign_ID());
                }
                if (tel.GetC_Project_ID() != 0)
                {
                    _order.SetC_Project_ID(tel.GetC_Project_ID());
                    //	Optionally Overwrite BP Price list from Project
                    MProject project = new MProject(GetCtx(), tel.GetC_Project_ID(), Get_TrxName());
                    if (project.GetM_PriceList_ID() != 0)
                    {
                        _order.SetM_PriceList_ID(project.GetM_PriceList_ID());
                    }
                }
                _order.SetSalesRep_ID(te.GetDoc_User_ID());
                //
                if (!_order.Save())
                {
                    throw new Exception("Cannot save Order");
                }
            }
            else
            {
                //	Update Header info
                if (tel.GetC_Activity_ID() != 0 && tel.GetC_Activity_ID() != _order.GetC_Activity_ID())
                {
                    _order.SetC_Activity_ID(tel.GetC_Activity_ID());
                }
                if (tel.GetC_Campaign_ID() != 0 && tel.GetC_Campaign_ID() != _order.GetC_Campaign_ID())
                {
                    _order.SetC_Campaign_ID(tel.GetC_Campaign_ID());
                }
                if (!_order.Save())
                {
                    new Exception("Cannot save Order");
                }
            }

            //	OrderLine
            MOrderLine ol = new MOrderLine(_order);

            //
            if (tel.GetM_Product_ID() != 0)
            {
                ol.SetM_Product_ID(tel.GetM_Product_ID(),
                                   tel.GetC_UOM_ID());
            }
            if (tel.GetS_ResourceAssignment_ID() != 0)
            {
                ol.SetS_ResourceAssignment_ID(tel.GetS_ResourceAssignment_ID());
            }
            // Set charge ID
            if (tel.GetC_Charge_ID() != 0)
            {
                ol.SetC_Charge_ID(tel.GetC_Charge_ID());
                ol.SetPriceActual(tel.GetExpenseAmt());
                ol.SetQty(tel.GetQty());
            }
            ol.SetQty(tel.GetQtyInvoiced());                    //
            ol.SetDescription(tel.GetDescription());
            //
            ol.SetC_Project_ID(tel.GetC_Project_ID());
            ol.SetC_ProjectPhase_ID(tel.GetC_ProjectPhase_ID());
            ol.SetC_ProjectTask_ID(tel.GetC_ProjectTask_ID());
            ol.SetC_Activity_ID(tel.GetC_Activity_ID());
            ol.SetC_Campaign_ID(tel.GetC_Campaign_ID());
            //
            Decimal price = tel.GetPriceInvoiced();     //

            if (price.CompareTo(Env.ZERO) != 0)
            {
                if (tel.GetC_Currency_ID() != _order.GetC_Currency_ID())
                {
                    price = MConversionRate.Convert(GetCtx(), price,
                                                    tel.GetC_Currency_ID(), _order.GetC_Currency_ID(),
                                                    _order.GetAD_Client_ID(), _order.GetAD_Org_ID());
                }
                ol.SetPrice(price);
            }
            else
            {
                ol.SetPrice();
            }
            if (tel.GetC_UOM_ID() != 0 && ol.GetC_UOM_ID() == 0)
            {
                ol.SetC_UOM_ID(tel.GetC_UOM_ID());
            }
            ol.SetTax();
            if (!ol.Save())
            {
                throw new Exception("Cannot save Order Line");
            }
            //	Update TimeExpense Line
            tel.SetC_OrderLine_ID(ol.GetC_OrderLine_ID());
            if (tel.Save())
            {
                log.Fine("Updated " + tel + " with C_OrderLine_ID");
            }
            else
            {
                log.Log(Level.SEVERE, "Not Updated " + tel + " with C_OrderLine_ID");
            }
        }       //	processLine
        /**
         *  Create Trial Asset
         *	@param ctx context
         *	@param user user
         *	@param entityType entity type
         *	@return asset or null if no product found
         */
        public static MAsset GetTrial(Ctx ctx, MUser user, String entityType)
        {
            if (user == null)
            {
                _log.Warning("Cannot create Trial - No User");
                return(null);
            }
            if (Util.IsEmpty(entityType))
            {
                _log.Warning("Cannot create Trial - No Entity Type");
                return(null);
            }
            MProduct product = MProduct.GetTrial(ctx, entityType);

            if (product == null)
            {
                _log.Warning("No Trial for Entity Type=" + entityType);
                return(null);
            }
            //
            DateTime now = Convert.ToDateTime(CommonFunctions.CurrentTimeMillis());
            //
            MAsset asset = new MAsset(ctx, 0, null);

            asset.SetClientOrg(user);
            asset.SetAssetServiceDate(now);
            asset.SetIsOwned(false);
            asset.SetIsTrialPhase(true);
            //
            MBPartner partner    = new MBPartner(ctx, user.GetC_BPartner_ID(), null);
            String    documentNo = "Trial";
            //	Value
            String value = partner.GetValue() + "_" + product.GetValue();

            if (value.Length > 40 - documentNo.Length)
            {
                value = value.Substring(0, 40 - documentNo.Length) + documentNo;
            }
            asset.SetValue(value);
            //	Name		MProduct.afterSave
            String name = "Trial " + partner.GetName() + " - " + product.GetName();

            if (name.Length > 60)
            {
                name = name.Substring(0, 60);
            }
            asset.SetName(name);
            //	Description
            String description = product.GetDescription();

            asset.SetDescription(description);

            //	User
            asset.SetAD_User_ID(user.GetAD_User_ID());
            asset.SetC_BPartner_ID(user.GetC_BPartner_ID());
            //	Product
            asset.SetM_Product_ID(product.GetM_Product_ID());
            asset.SetA_Asset_Group_ID(product.GetA_Asset_Group_ID());
            asset.SetQty(new Decimal(product.GetSupportUnits()));
            //	Guarantee & Version
            asset.SetGuaranteeDate(TimeUtil.AddDays(now, product.GetTrialPhaseDays()));
            asset.SetVersionNo(product.GetVersionNo());
            //
            return(asset);
        }
Exemple #7
0
        }   //	doIt

        /// <summary>
        /// Process Expense Line
        /// </summary>
        /// <param name="te">header</param>
        /// <param name="tel">line</param>
        /// <param name="bp">bp</param>
        private void ProcessLine(MTimeExpense te, MTimeExpenseLine tel, MBPartner bp)
        {
            if (_order == null)
            {
                log.Info("New Order for " + bp + ", Project=" + tel.GetC_Project_ID());
                _order = new MOrder(GetCtx(), 0, Get_TrxName());
                _order.SetAD_Org_ID(tel.GetAD_Org_ID());
                _order.SetC_DocTypeTarget_ID(MOrder.DocSubTypeSO_Standard);
                //
                _order.SetBPartner(bp);
                if (_order.GetC_BPartner_Location_ID() == 0)
                {
                    log.Log(Level.SEVERE, "No BP Location: " + bp);
                    AddLog(0, te.GetDateReport(),
                           null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName());
                    _order = null;
                    return;
                }
                _order.SetM_Warehouse_ID(te.GetM_Warehouse_ID());
                //Bhupendra: Add payment term
                // to check for if payment term is null
                if (bp.GetC_PaymentTerm_ID() == 0)
                {
                    // set the default payment method as check
                    int payTerm = GetPaymentTerm();
                    if (payTerm <= 0)
                    {
                        message = Msg.GetMsg(GetCtx(), "IsActivePaymentTerm");
                        return;
                    }
                    else
                    {
                        _order.SetC_PaymentTerm_ID(payTerm);
                    }
                }
                else
                {
                    //check weather paymentterm is active or not
                    if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM C_PaymentTerm WHERE C_PaymentTerm_ID=" + bp.GetC_PaymentTerm_ID(), null, Get_Trx())).Equals("Y"))
                    {
                        _order.SetC_PaymentTerm_ID(bp.GetC_PaymentTerm_ID());
                    }
                    else
                    {
                        message = Msg.GetMsg(GetCtx(), "IsActivePaymentTerm");
                        return;
                    }
                }
                // Bhupendra: added a cond to check for payment method if null
                // Added by mohit - to set payment method and sales rep id.
                if (bp.GetVA009_PaymentMethod_ID() == 0)
                {
                    // set the default payment method as check
                    int paymethod = GetPaymentMethod();
                    if (paymethod <= 0)
                    {
                        message = Msg.GetMsg(GetCtx(), "IsActivePaymentMethod");
                        return;
                    }
                    else
                    {
                        _order.SetVA009_PaymentMethod_ID(paymethod);
                    }
                }
                else
                {
                    //check weather the PaymentMethod is active or not
                    if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID=" + bp.GetVA009_PaymentMethod_ID(), null, Get_Trx())).Equals("Y"))
                    {
                        _order.SetVA009_PaymentMethod_ID(bp.GetVA009_PaymentMethod_ID());
                    }
                    else
                    {
                        message = Msg.GetMsg(GetCtx(), "IsActivePaymentMethod");
                        return;
                    }
                }
                _order.SetSalesRep_ID(te.GetDoc_User_ID());

                ////Added By Arpit asked by Surya Sir..................29-12-2015
                //_order.SetSalesRep_ID(GetCtx().GetAD_User_ID());
                //End
                if (tel.GetC_Activity_ID() != 0)
                {
                    _order.SetC_Activity_ID(tel.GetC_Activity_ID());
                }
                if (tel.GetC_Campaign_ID() != 0)
                {
                    _order.SetC_Campaign_ID(tel.GetC_Campaign_ID());
                }
                if (tel.GetC_Project_ID() != 0)
                {
                    _order.SetC_Project_ID(tel.GetC_Project_ID());
                    //	Optionally Overwrite BP Price list from Project
                    MProject project = new MProject(GetCtx(), tel.GetC_Project_ID(), Get_TrxName());
                    if (project.GetM_PriceList_ID() != 0)
                    {
                        //check weather the PriceList is active or not
                        if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM M_PriceList WHERE M_PriceList_ID=" + project.GetM_PriceList_ID(), null, Get_Trx())).Equals("Y"))
                        {
                            _order.SetM_PriceList_ID(project.GetM_PriceList_ID());
                        }
                        else
                        {
                            message = Msg.GetMsg(GetCtx(), "IsActivePriceList");
                            return;
                        }
                    }
                }
                else
                {
                    if (bp.GetM_PriceList_ID() != 0)
                    {
                        if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM M_PriceList WHERE M_PriceList_ID=" + bp.GetM_PriceList_ID(), null, Get_Trx())).Equals("Y"))
                        {
                            _order.SetM_PriceList_ID(bp.GetM_PriceList_ID());
                        }
                        else
                        {
                            message = Msg.GetMsg(GetCtx(), "IsActivePriceList");
                            return;
                        }
                    }
                }
                _order.SetSalesRep_ID(te.GetDoc_User_ID());
                //
                if (!_order.Save())
                {
                    Rollback();
                    ValueNamePair pp = VLogger.RetrieveError();
                    if (pp != null)
                    {
                        message = pp.GetName();
                        //if GetName is Empty then it will check GetValue
                        if (string.IsNullOrEmpty(message))
                        {
                            message = Msg.GetMsg("", pp.GetValue());
                        }
                    }
                    if (string.IsNullOrEmpty(message))
                    {
                        message = Msg.GetMsg(GetCtx(), "CantSaveOrder");
                    }
                    return;
                    //throw new Exception("Cannot save Order");
                }
            }
            else
            {
                //	Update Header info
                if (tel.GetC_Activity_ID() != 0 && tel.GetC_Activity_ID() != _order.GetC_Activity_ID())
                {
                    _order.SetC_Activity_ID(tel.GetC_Activity_ID());
                }
                if (tel.GetC_Campaign_ID() != 0 && tel.GetC_Campaign_ID() != _order.GetC_Campaign_ID())
                {
                    _order.SetC_Campaign_ID(tel.GetC_Campaign_ID());
                }
                if (!_order.Save())
                {
                    Rollback();
                    //get error message from ValueNamePair
                    ValueNamePair pp = VLogger.RetrieveError();
                    if (pp != null)
                    {
                        message = pp.GetName();
                        //if GetName is Empty then it will check GetValue
                        if (string.IsNullOrEmpty(message))
                        {
                            message = Msg.GetMsg("", pp.GetValue());
                        }
                    }
                    //it will check message is null or not
                    if (string.IsNullOrEmpty(message))
                    {
                        message = Msg.GetMsg(GetCtx(), "CantSaveOrder");
                    }
                    return;
                    //new Exception("Cannot save Order");
                }
            }

            //	OrderLine
            MOrderLine ol = new MOrderLine(_order);

            //
            if (tel.GetM_Product_ID() != 0)
            {
                ol.SetM_Product_ID(tel.GetM_Product_ID(),
                                   tel.GetC_UOM_ID());
            }
            if (tel.GetS_ResourceAssignment_ID() != 0)
            {
                ol.SetS_ResourceAssignment_ID(tel.GetS_ResourceAssignment_ID());
            }
            // Set charge ID
            if (tel.GetC_Charge_ID() != 0)
            {
                ol.SetC_Charge_ID(tel.GetC_Charge_ID());
                ol.SetPriceActual(tel.GetExpenseAmt());
                ol.SetQty(tel.GetQty());
            }
            ol.SetQty(tel.GetQtyInvoiced());        //
            ol.SetDescription(tel.GetDescription());
            //
            ol.SetC_Project_ID(tel.GetC_Project_ID());
            ol.SetC_ProjectPhase_ID(tel.GetC_ProjectPhase_ID());
            ol.SetC_ProjectTask_ID(tel.GetC_ProjectTask_ID());
            ol.SetC_Activity_ID(tel.GetC_Activity_ID());
            ol.SetC_Campaign_ID(tel.GetC_Campaign_ID());
            //
            Decimal price = tel.GetPriceInvoiced(); //

            if (price.CompareTo(Env.ZERO) != 0)
            {
                if (tel.GetC_Currency_ID() != _order.GetC_Currency_ID())
                {
                    price = MConversionRate.Convert(GetCtx(), price,
                                                    tel.GetC_Currency_ID(), _order.GetC_Currency_ID(),
                                                    _order.GetAD_Client_ID(), _order.GetAD_Org_ID());
                }
                ol.SetPrice(price);
                // added by Bhupendra to set the entered price
                ol.SetPriceEntered(price);
            }
            else
            {
                ol.SetPrice();
            }
            if (tel.GetC_UOM_ID() != 0 && ol.GetC_UOM_ID() == 0)
            {
                ol.SetC_UOM_ID(tel.GetC_UOM_ID());
            }
            ol.SetTax();
            if (!ol.Save())
            {
                Rollback();
                //get error message from ValueNamePair
                ValueNamePair pp = VLogger.RetrieveError();
                if (pp != null)
                {
                    message = pp.GetName();
                    //if GetName is Empty then it will check GetValue
                    if (string.IsNullOrEmpty(message))
                    {
                        message = Msg.GetMsg("", pp.GetValue());
                    }
                }
                //it will check message is null or not
                if (string.IsNullOrEmpty(message))
                {
                    message = Msg.GetMsg(GetCtx(), "CantSaveOrderLine");
                }
                return;
                //throw new Exception("Cannot save Order Line");
            }
            //	Update TimeExpense Line
            tel.SetC_OrderLine_ID(ol.GetC_OrderLine_ID());
            if (tel.Save())
            {
                log.Fine("Updated " + tel + " with C_OrderLine_ID");
            }
            else
            {
                log.Log(Level.SEVERE, "Not Updated " + tel + " with C_OrderLine_ID");
            }
        }   //	processLine
        }       //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (clear text)</returns>
        protected override String DoIt()
        {
            int           index = 1;
            StringBuilder sql   = new StringBuilder("SELECT * "
                                                    + "FROM S_TimeExpense e "
                                                    + "WHERE e.Processed='Y'"
                                                    + " AND e.AD_Client_ID=@param1"); //	#1

            if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1)
            {
                index++;
                sql.Append(" AND e.C_BPartner_ID=@param2");     //	#2
            }
            if (_DateFrom != null)
            {
                index++;
                sql.Append(" AND e.DateReport >=@param3");      //	#3
            }
            if (_DateTo != null)
            {
                index++;
                sql.Append(" AND e.DateReport <=@param4");      //	#4
                sql.Append(" AND EXISTS (SELECT * FROM S_TimeExpenseLine el "
                           + "WHERE e.S_TimeExpense_ID=el.S_TimeExpense_ID"
                           + " AND el.C_InvoiceLine_ID IS NULL"
                           + " AND el.ConvertedAmt<>0) "
                           + "ORDER BY e.C_BPartner_ID, e.S_TimeExpense_ID");
            }
            //
            int      old_BPartner_ID = -1;
            MInvoice invoice         = null;

            //
            //PreparedStatement pstmt = null;
            SqlParameter[] param = new SqlParameter[index];
            IDataReader    idr   = null;
            DataTable      dt    = null;

            try
            {
                //pstmt = DataBase.prepareStatement (sql.toString (), get_TrxName());
                int par = 0;
                //pstmt.setInt(par++, getAD_Client_ID());
                param[0] = new SqlParameter("@param1", GetAD_Client_ID());
                if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1)
                {
                    par++;
                    //pstmt.setInt (par++, _C_BPartner_ID);
                    param[par] = new SqlParameter("@param2", _C_BPartner_ID);
                }
                if (_DateFrom != null)
                {
                    par++;
                    //pstmt.setTimestamp (par++, _DateFrom);
                    param[par] = new SqlParameter("@param3", _DateFrom);
                }
                if (_DateTo != null)
                {
                    par++;
                    //pstmt.setTimestamp (par++, _DateTo);
                    param[par] = new SqlParameter("@param4", _DateTo);
                }
                //ResultSet rs = pstmt.executeQuery ();
                idr = DataBase.DB.ExecuteReader(sql.ToString(), param, Get_TrxName());
                dt  = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                //	********* Expense Line Loop
                {
                    MTimeExpense te = new MTimeExpense(GetCtx(), dr, Get_TrxName());

                    //	New BPartner - New Order
                    if (te.GetC_BPartner_ID() != old_BPartner_ID)
                    {
                        CompleteInvoice(invoice);
                        MBPartner bp = new MBPartner(GetCtx(), te.GetC_BPartner_ID(), Get_TrxName());
                        //
                        log.Info("New Invoice for " + bp);
                        invoice = new MInvoice(GetCtx(), 0, null);
                        invoice.SetClientOrg(te.GetAD_Client_ID(), te.GetAD_Org_ID());
                        invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE);      //	API
                        invoice.SetDocumentNo(te.GetDocumentNo());
                        //
                        invoice.SetBPartner(bp);
                        if (invoice.GetC_BPartner_Location_ID() == 0)
                        {
                            log.Log(Level.SEVERE, "No BP Location: " + bp);
                            AddLog(0, te.GetDateReport(),
                                   null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName());
                            invoice = null;
                            break;
                        }
                        invoice.SetM_PriceList_ID(te.GetM_PriceList_ID());
                        invoice.SetSalesRep_ID(te.GetDoc_User_ID());
                        String descr = Msg.Translate(GetCtx(), "S_TimeExpense_ID")
                                       + ": " + te.GetDocumentNo() + " "
                                       + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport());
                        invoice.SetDescription(descr);
                        if (!invoice.Save())
                        {
                            new Exception("Cannot save Invoice");
                        }
                        old_BPartner_ID = bp.GetC_BPartner_ID();
                    }
                    MTimeExpenseLine[] tel = te.GetLines(false);
                    for (int i = 0; i < tel.Length; i++)
                    {
                        MTimeExpenseLine line = tel[i];

                        //	Already Invoiced or nothing to be reimbursed
                        if (line.GetC_InvoiceLine_ID() != 0 ||
                            Env.ZERO.CompareTo(line.GetQtyReimbursed()) == 0 ||
                            Env.ZERO.CompareTo(line.GetPriceReimbursed()) == 0)
                        {
                            continue;
                        }
                        //	Update Header info
                        if (line.GetC_Activity_ID() != 0 && line.GetC_Activity_ID() != invoice.GetC_Activity_ID())
                        {
                            invoice.SetC_Activity_ID(line.GetC_Activity_ID());
                        }
                        if (line.GetC_Campaign_ID() != 0 && line.GetC_Campaign_ID() != invoice.GetC_Campaign_ID())
                        {
                            invoice.SetC_Campaign_ID(line.GetC_Campaign_ID());
                        }
                        if (line.GetC_Project_ID() != 0 && line.GetC_Project_ID() != invoice.GetC_Project_ID())
                        {
                            invoice.SetC_Project_ID(line.GetC_Project_ID());
                        }
                        if (!invoice.Save())
                        {
                            new Exception("Cannot save Invoice");
                        }

                        //	Create OrderLine
                        MInvoiceLine il = new MInvoiceLine(invoice);
                        //
                        if (line.GetM_Product_ID() != 0)
                        {
                            il.SetM_Product_ID(line.GetM_Product_ID(), true);
                        }
                        il.SetQty(line.GetQtyReimbursed());             //	Entered/Invoiced
                        il.SetDescription(line.GetDescription());
                        //
                        il.SetC_Project_ID(line.GetC_Project_ID());
                        il.SetC_ProjectPhase_ID(line.GetC_ProjectPhase_ID());
                        il.SetC_ProjectTask_ID(line.GetC_ProjectTask_ID());
                        il.SetC_Activity_ID(line.GetC_Activity_ID());
                        il.SetC_Campaign_ID(line.GetC_Campaign_ID());
                        //
                        //	il.setPrice();	//	not really a list/limit price for reimbursements
                        il.SetPrice(line.GetPriceReimbursed()); //
                        il.SetTax();
                        if (!il.Save())
                        {
                            new Exception("Cannot save Invoice Line");
                        }
                        //	Update TEL
                        line.SetC_InvoiceLine_ID(il.GetC_InvoiceLine_ID());
                        line.SetIsInvoiced(true);
                        line.Save();
                    }   //	for all expense lines
                }       //	********* Expense Line Loop
                dt = null;
                //dt.Clear();
            }
            catch (Exception e)
            {
                if (dt != null)
                {
                    dt = null;
                }
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql.ToString(), e);
            }
            finally
            {
                if (dt != null)
                {
                    dt = null;
                }
                if (idr != null)
                {
                    idr.Close();
                }
            }
            CompleteInvoice(invoice);
            if (_noInvoices == 0)
            {
                return(" @No Record Found for Invoice  Creation@");
            }
            return("" + _noInvoices + " @Invoices Generated Successfully@");
        }       //	doIt
Exemple #9
0
        /**
         *  Generate Shipments
         *  @param pstmt order query
         *	@return info
         */
        private String Generate(IDataReader idr)
        {
            DataTable dt = new DataTable();

            try
            {
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)//  while (dr.next ())
                {
                    MOrder order = new MOrder(GetCtx(), dr, Get_TrxName());

                    // Credit Limit check added by Vivek on 24/08/2016
                    MBPartner bp = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                    if (bp.GetCreditStatusSettingOn() == "CH")
                    {
                        decimal creditLimit = bp.GetSO_CreditLimit();
                        string  creditVal   = bp.GetCreditValidation();
                        if (creditLimit != 0)
                        {
                            decimal creditAvlb = creditLimit - bp.GetSO_CreditUsed();
                            if (creditAvlb <= 0)
                            {
                                if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                                {
                                    AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName());
                                    continue;
                                }
                                else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                                {
                                    if (_msg != null)
                                    {
                                        _msg.Clear();
                                    }
                                    _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                                    //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName());
                                }
                            }
                        }
                    }
                    else
                    {
                        MBPartnerLocation bpl      = new MBPartnerLocation(GetCtx(), order.GetC_BPartner_Location_ID(), null);
                        MBPartner         bpartner = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                        if (bpl.GetCreditStatusSettingOn() == "CL")
                        {
                            decimal creditLimit = bpl.GetSO_CreditLimit();
                            string  creditVal   = bpl.GetCreditValidation();
                            if (creditLimit != 0)
                            {
                                decimal creditAvlb = creditLimit - bpl.GetSO_CreditUsed();
                                if (creditAvlb <= 0)
                                {
                                    if (creditVal == "C" || creditVal == "D" || creditVal == "F")
                                    {
                                        AddLog(Msg.GetMsg(GetCtx(), "StopInvoice") + bp.GetName() + " " + bpl.GetName());
                                        continue;
                                    }
                                    else if (creditVal == "I" || creditVal == "J" || creditVal == "L")
                                    {
                                        if (_msg != null)
                                        {
                                            _msg.Clear();
                                        }
                                        _msg.Append(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                                        //AddLog(Msg.GetMsg(GetCtx(), "WarningInvoice") + bp.GetName() + " " + bpl.GetName());
                                    }
                                }
                            }
                        }
                    }
                    // Credit Limit End

                    //	New Invoice Location
                    if (!_ConsolidateDocument ||
                        (_invoice != null &&
                         (_invoice.GetC_BPartner_Location_ID() != order.GetBill_Location_ID() ||
                          _invoice.GetC_PaymentTerm_ID() != order.GetC_PaymentTerm_ID())))
                    {
                        CompleteInvoice();
                    }
                    bool completeOrder = MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule());

                    //	Schedule After Delivery
                    bool doInvoice = false;
                    if (MOrder.INVOICERULE_CustomerScheduleAfterDelivery.Equals(order.GetInvoiceRule()))
                    {
                        _bp = new MBPartner(GetCtx(), order.GetBill_BPartner_ID(), null);
                        if (_bp.GetC_InvoiceSchedule_ID() == 0)
                        {
                            log.Warning("BPartner has no Schedule - set to After Delivery");
                            order.SetInvoiceRule(MOrder.INVOICERULE_AfterDelivery);
                            order.Save();
                        }
                        else
                        {
                            MInvoiceSchedule ins = MInvoiceSchedule.Get(GetCtx(), _bp.GetC_InvoiceSchedule_ID(), Get_TrxName());
                            if (ins.CanInvoice(order.GetDateOrdered(), order.GetGrandTotal()))
                            {
                                doInvoice = true;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }   //	Schedule

                    //	After Delivery
                    if (doInvoice || MOrder.INVOICERULE_AfterDelivery.Equals(order.GetInvoiceRule()))
                    {
                        MInOut       shipment      = null;
                        MInOutLine[] shipmentLines = order.GetShipmentLines();
                        MOrderLine[] oLines        = order.GetLines(true, null);
                        for (int i = 0; i < shipmentLines.Length; i++)
                        {
                            MInOutLine shipLine = shipmentLines[i];
                            if (shipLine.IsInvoiced())
                            {
                                continue;
                            }
                            if (shipment == null ||
                                shipment.GetM_InOut_ID() != shipLine.GetM_InOut_ID())
                            {
                                shipment = new MInOut(GetCtx(), shipLine.GetM_InOut_ID(), Get_TrxName());
                            }
                            if (!shipment.IsComplete() ||       //	ignore incomplete or reversals
                                shipment.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed))
                            {
                                continue;
                            }
                            //
                            CreateLine(order, shipment, shipLine);
                        }       //	shipment lines
                        for (int i = 0; i < oLines.Length; i++)
                        {
                            MOrderLine oLine = oLines[i];
                            if (oLine.GetC_Charge_ID() > 0)
                            {
                                Decimal toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                                log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine);
                                Decimal qtyEntered = toInvoice;
                                //	Correct UOM for QtyEntered
                                if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                                {
                                    qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                                  toInvoice, oLine.GetQtyEntered()),
                                                                              oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                                }
                                //
                                if (oLine.IsContract() == false)
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                        }
                    }
                    //	After Order Delivered, Immediate
                    else
                    {
                        MOrderLine[] oLines = order.GetLines(true, null);
                        for (int i = 0; i < oLines.Length; i++)
                        {
                            MOrderLine oLine     = oLines[i];
                            Decimal    toInvoice = Decimal.Subtract(oLine.GetQtyOrdered(), oLine.GetQtyInvoiced());
                            if (toInvoice.CompareTo(Env.ZERO) == 0 && oLine.GetM_Product_ID() != 0)
                            {
                                continue;
                            }
                            //
                            bool fullyDelivered = oLine.GetQtyOrdered().CompareTo(oLine.GetQtyDelivered()) == 0;

                            //	Complete Order
                            if (completeOrder && !fullyDelivered)
                            {
                                log.Fine("Failed CompleteOrder - " + oLine);
                                completeOrder = false;
                                break;
                            }
                            //	Immediate
                            else if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule()))
                            {
                                log.Fine("Immediate - ToInvoice=" + toInvoice + " - " + oLine);
                                Decimal qtyEntered = toInvoice;
                                //	Correct UOM for QtyEntered
                                if (oLine.GetQtyEntered().CompareTo(oLine.GetQtyOrdered()) != 0)
                                {
                                    qtyEntered = Decimal.Round(Decimal.Divide(Decimal.Multiply(
                                                                                  toInvoice, oLine.GetQtyEntered()),
                                                                              oLine.GetQtyOrdered()), 12, MidpointRounding.AwayFromZero);
                                }
                                //
                                if (oLine.IsContract() == false)
                                {
                                    CreateLine(order, oLine, toInvoice, qtyEntered);
                                    log.Info("ID " + oLine.Get_ID() + "Qty Ordered " + oLine.GetQtyOrdered() + " Qty Invoiced " + oLine.GetQtyInvoiced());
                                }
                            }
                            else
                            {
                                log.Fine("Failed: " + order.GetInvoiceRule()
                                         + " - ToInvoice=" + toInvoice + " - " + oLine);
                            }
                        }       //	for all order lines
                        if (MOrder.INVOICERULE_Immediate.Equals(order.GetInvoiceRule()))
                        {
                            _line += 1000;
                        }
                    }

                    //	Complete Order successful
                    if (completeOrder && MOrder.INVOICERULE_AfterOrderDelivered.Equals(order.GetInvoiceRule()))
                    {
                        MInOut[] shipments = order.GetShipments(true);
                        for (int i = 0; i < shipments.Length; i++)
                        {
                            MInOut ship = shipments[i];
                            if (!ship.IsComplete() ||           //	ignore incomplete or reversals
                                ship.GetDocStatus().Equals(MInOut.DOCSTATUS_Reversed))
                            {
                                continue;
                            }
                            MInOutLine[] shipLines = ship.GetLines(false);
                            for (int j = 0; j < shipLines.Length; j++)
                            {
                                MInOutLine shipLine = shipLines[j];
                                if (!order.IsOrderLine(shipLine.GetC_OrderLine_ID()))
                                {
                                    continue;
                                }
                                if (!shipLine.IsInvoiced())
                                {
                                    CreateLine(order, ship, shipLine);
                                }
                            } //	lines
                            _line += 1000;
                        }     //	all shipments
                    }         //	complete Order
                }             //	for all orders
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "", e);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }

                dt = null;
            }

            CompleteInvoice();
            return("@Created@ = " + _created);
        }
Exemple #10
0
        }       //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (clear text)</returns>
        protected override String DoIt()
        {
            int           index = 1;
            StringBuilder sql   = new StringBuilder("SELECT * "
                                                    + "FROM S_TimeExpense e "
                                                    + "WHERE e.Processed='Y'"
                                                    + " AND e.AD_Client_ID=@param1"); //	#1

            if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1)
            {
                index++;
                sql.Append(" AND e.C_BPartner_ID=@param2");     //	#2
            }
            if (_DateFrom != null)
            {
                index++;
                sql.Append(" AND e.DateReport >=@param3");      //	#3
            }
            if (_DateTo != null)
            {
                index++;
                sql.Append(" AND e.DateReport <=@param4");      //	#4
            }
            // JID_0868
            // chanegs done by Bharat on 12 September 2018 to handle the case if invoice is created with an expense for the selected Business Partner
            sql.Append(" AND EXISTS (SELECT * FROM S_TimeExpenseLine el "
                       + "WHERE e.S_TimeExpense_ID=el.S_TimeExpense_ID"
                       + " AND el.C_InvoiceLine_ID IS NULL"
                       + " AND el.ConvertedAmt<>0) "
                       + "ORDER BY e.C_BPartner_ID, e.S_TimeExpense_ID");

            //
            int      old_BPartner_ID = -1;
            MInvoice invoice         = null;

            //
            //PreparedStatement pstmt = null;
            SqlParameter[] param = new SqlParameter[index];
            IDataReader    idr   = null;
            DataTable      dt    = null;

            try
            {
                //pstmt = DataBase.prepareStatement (sql.toString (), get_TrxName());
                int par = 0;
                //pstmt.setInt(par++, getAD_Client_ID());
                param[0] = new SqlParameter("@param1", GetAD_Client_ID());
                if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1)
                {
                    par++;
                    //pstmt.setInt (par++, _C_BPartner_ID);
                    param[par] = new SqlParameter("@param2", _C_BPartner_ID);
                }
                if (_DateFrom != null)
                {
                    par++;
                    //pstmt.setTimestamp (par++, _DateFrom);
                    param[par] = new SqlParameter("@param3", _DateFrom);
                }
                if (_DateTo != null)
                {
                    par++;
                    //pstmt.setTimestamp (par++, _DateTo);
                    param[par] = new SqlParameter("@param4", _DateTo);
                }
                //ResultSet rs = pstmt.executeQuery ();
                idr = DataBase.DB.ExecuteReader(sql.ToString(), param, Get_TrxName());
                dt  = new DataTable();
                dt.Load(idr);
                idr.Close();
                foreach (DataRow dr in dt.Rows)
                //	********* Expense Line Loop
                {
                    MTimeExpense te = new MTimeExpense(GetCtx(), dr, Get_TrxName());

                    //	New BPartner - New Order
                    if (te.GetC_BPartner_ID() != old_BPartner_ID)
                    {
                        CompleteInvoice(invoice);
                        MBPartner bp = new MBPartner(GetCtx(), te.GetC_BPartner_ID(), Get_TrxName());
                        //
                        log.Info("New Invoice for " + bp);
                        invoice = new MInvoice(GetCtx(), 0, null);
                        invoice.SetIsExpenseInvoice(true); //added by arpit asked by Surya Sir on DEC 28,2015
                        invoice.SetClientOrg(te.GetAD_Client_ID(), te.GetAD_Org_ID());

                        // JID_0868
                        // chanegs done by Bharat on 12 September 2018 to set the document type where Expense Invoice checkbox is true.
                        String qry = "SELECT C_DocType_ID FROM C_DocType "
                                     + "WHERE AD_Client_ID=@param1 AND DocBaseType=@param2"
                                     + " AND IsActive='Y' AND IsExpenseInvoice = 'Y' "
                                     + "ORDER BY C_DocType_ID DESC ,   IsDefault DESC";
                        int C_DocType_ID = DB.GetSQLValue(null, qry, GetAD_Client_ID(), MDocBaseType.DOCBASETYPE_APINVOICE);
                        if (C_DocType_ID <= 0)
                        {
                            log.Log(Level.SEVERE, "Not found for AC_Client_ID="
                                    + GetAD_Client_ID() + " - " + MDocBaseType.DOCBASETYPE_APINVOICE);
                        }
                        else
                        {
                            log.Fine(MDocBaseType.DOCBASETYPE_APINVOICE);
                        }
                        invoice.SetC_DocTypeTarget_ID(C_DocType_ID);
                        //invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE);	//	API

                        //commented by Arpit on Jan 4,2015       Mentis issue no.   0000310
                        //invoice.SetDocumentNo(te.GetDocumentNo());
                        //
                        invoice.SetBPartner(bp);
                        if (invoice.GetC_BPartner_Location_ID() == 0)
                        {
                            log.Log(Level.SEVERE, "No BP Location: " + bp);
                            AddLog(0, te.GetDateReport(),
                                   null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName());
                            invoice = null;
                            break;
                        }
                        invoice.SetM_PriceList_ID(te.GetM_PriceList_ID());
                        invoice.SetSalesRep_ID(te.GetDoc_User_ID());
                        String descr = Msg.Translate(GetCtx(), "S_TimeExpense_ID")
                                       + ": " + te.GetDocumentNo() + " "
                                       + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport());
                        invoice.SetDescription(descr);
                        if (!invoice.Save())
                        {
                            //return GetReterivedError(invoice, "Cannot save Invoice");
                            new Exception("Cannot save Invoice");
                        }
                        //added by arpit asked by Surya Sir on 29/12/2015*******
                        else
                        {
                            old_BPartner_ID = bp.GetC_BPartner_ID();
                        }
                        //end***************
                    }
                    // JID_0868
                    //Description include all document numbers which is come from Time And Expense Recording window to expense invoice in case of multiple records
                    else if (old_BPartner_ID > 0)
                    {
                        String descr = invoice.GetDescription() + "\n" + Msg.Translate(GetCtx(), "S_TimeExpense_ID")
                                       + ": " + te.GetDocumentNo() + " "
                                       + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport());
                        invoice.SetDescription(descr);
                    }
                    MTimeExpenseLine[] tel = te.GetLines(false);
                    for (int i = 0; i < tel.Length; i++)
                    {
                        MTimeExpenseLine line = tel[i];

                        //	Already Invoiced or nothing to be reimbursed
                        if (line.GetC_InvoiceLine_ID() != 0 ||
                            Env.ZERO.CompareTo(line.GetQtyReimbursed()) == 0 ||
                            Env.ZERO.CompareTo(line.GetPriceReimbursed()) == 0)
                        {
                            continue;
                        }
                        //	Update Header info
                        if (line.GetC_Activity_ID() != 0 && line.GetC_Activity_ID() != invoice.GetC_Activity_ID())
                        {
                            invoice.SetC_Activity_ID(line.GetC_Activity_ID());
                        }
                        if (line.GetC_Campaign_ID() != 0 && line.GetC_Campaign_ID() != invoice.GetC_Campaign_ID())
                        {
                            invoice.SetC_Campaign_ID(line.GetC_Campaign_ID());
                        }
                        if (line.GetC_Project_ID() != 0 && line.GetC_Project_ID() != invoice.GetC_Project_ID())
                        {
                            invoice.SetC_Project_ID(line.GetC_Project_ID());
                        }
                        if (!invoice.Save())
                        {
                            //return GetReterivedError(invoice, "Cannot save Invoice");
                            new Exception("Cannot save Invoice");
                        }

                        //	Create OrderLine
                        MInvoiceLine il = new MInvoiceLine(invoice);
                        //
                        if (line.GetM_Product_ID() != 0)
                        {
                            il.SetM_Product_ID(line.GetM_Product_ID(), true);
                        }
                        //added by arpit asked by Surya Sir on 28/12/2015_____***************************
                        if (line.GetC_Charge_ID() != 0)
                        {
                            il.SetC_Charge_ID(line.GetC_Charge_ID());
                        }
                        //end here *****************************
                        il.SetQty(line.GetQtyReimbursed());             //	Entered/Invoiced
                        il.SetDescription(line.GetDescription());
                        //
                        il.SetC_Project_ID(line.GetC_Project_ID());
                        il.SetC_ProjectPhase_ID(line.GetC_ProjectPhase_ID());
                        il.SetC_ProjectTask_ID(line.GetC_ProjectTask_ID());
                        il.SetC_Activity_ID(line.GetC_Activity_ID());
                        il.SetC_Campaign_ID(line.GetC_Campaign_ID());
                        //
                        //	il.setPrice();	//	not really a list/limit price for reimbursements
                        il.SetPrice(line.GetPriceReimbursed()); //

                        // JID_0868
                        // chanegs done by Bharat on 12 September 2018 to set the Amount in List price column.
                        il.SetPriceList(line.GetPriceReimbursed());
                        il.SetTax();
                        if (!il.Save())
                        {
                            //return GetReterivedError(il, "Cannot save Invoice");
                            new Exception("Cannot save Invoice Line");
                        }
                        //	Update TEL
                        line.SetC_InvoiceLine_ID(il.GetC_InvoiceLine_ID());
                        line.SetIsInvoiced(true);
                        line.Save();
                    }   //	for all expense lines
                }       //	********* Expense Line Loop
                dt = null;
                //dt.Clear();
            }
            catch (Exception e)
            {
                if (dt != null)
                {
                    dt = null;
                }
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql.ToString(), e);
            }
            finally
            {
                if (dt != null)
                {
                    dt = null;
                }
                if (idr != null)
                {
                    idr.Close();
                }
            }
            CompleteInvoice(invoice);
            if (_noInvoices == 0)
            {
                return(" @No Record Found for Invoice  Creation@");
            }
            return("" + _noInvoices + " @Invoices Generated Successfully@");
        }       //	doIt
        /// <summary>
        /// Create PO for Vendor
        /// </summary>
        /// <param name="C_BPartner_ID">vendor</param>
        /// <param name="so">sales order</param>
        /// <returns>MOrder</returns>
        public MOrder CreatePOForVendor(int C_BPartner_ID, MOrder so, string _shipDrop)
        {
            MOrder po = new MOrder(GetCtx(), 0, Get_TrxName());

            po.SetClientOrg(so.GetAD_Client_ID(), so.GetAD_Org_ID());
            po.SetRef_Order_ID(so.GetC_Order_ID());
            po.SetIsSOTrx(false);
            // method edited to set unreleased document type for PO
            po.SetC_DocTypeTarget_ID(false);
            //
            po.SetDescription(so.GetDescription());
            po.SetPOReference(so.GetDocumentNo());
            po.SetPriorityRule(so.GetPriorityRule());
            po.SetSalesRep_ID(so.GetSalesRep_ID());
            // Code Commented by Vivek Kumar on 20/09/2017 Assigned By Pradeep for drop shipment
            //po.SetM_Warehouse_ID(so.GetM_Warehouse_ID());
            //	Set Vendor
            MBPartner vendor = new MBPartner(GetCtx(), C_BPartner_ID, Get_TrxName());

            if (Env.IsModuleInstalled("VA009_"))
            {
                // Set PO Payment Method from Vendor
                if (Util.GetValueOfInt(vendor.GetVA009_PO_PaymentMethod_ID()) > 0)
                {
                    po.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(vendor.GetVA009_PO_PaymentMethod_ID()));
                }
                else
                {
                    if (string.IsNullOrEmpty(messageErrorOrSetting.ToString()))
                    {
                        messageErrorOrSetting.Append(Msg.GetMsg(GetCtx(), "VIS_PaymentMethodNotDefined") + " : " + vendor.GetName());
                    }
                    else
                    {
                        messageErrorOrSetting.Append(" , " + Msg.GetMsg(GetCtx(), "VIS_PaymentMethodNotDefined") + " : " + vendor.GetName());
                    }
                    po = null;
                    return(po);
                }
            }

            //JID_1252: If Vendor do not have Po Pricelist bind. System should give message.
            if (vendor.GetPO_PriceList_ID() > 0)
            {
                po.SetM_PriceList_ID(vendor.GetPO_PriceList_ID());
            }
            else
            {
                if (string.IsNullOrEmpty(messageErrorOrSetting.ToString()))
                {
                    messageErrorOrSetting.Append(Msg.GetMsg(GetCtx(), "VIS_VendorPrcListNotDefine") + " : " + vendor.GetName());
                }
                else
                {
                    messageErrorOrSetting.Append(" , " + Msg.GetMsg(GetCtx(), "VIS_VendorPrcListNotDefine") + " : " + vendor.GetName());
                }
                po = null;
                return(po);
            }

            // JID_1262: If Payment Term is not bind BP, BP Group and No Default Payment Term. System do not create PO neither give message.
            if (vendor.GetPO_PaymentTerm_ID() > 0)
            {
                po.SetC_PaymentTerm_ID(vendor.GetPO_PaymentTerm_ID());
            }
            else
            {
                if (string.IsNullOrEmpty(messageErrorOrSetting.ToString()))
                {
                    messageErrorOrSetting.Append(Msg.GetMsg(GetCtx(), "VIS_VendorPaytemNotDefine") + " : " + vendor.GetName());
                }
                else
                {
                    messageErrorOrSetting.Append(" , " + Msg.GetMsg(GetCtx(), "VIS_VendorPaytemNotDefine") + " : " + vendor.GetName());
                }
                po = null;
                return(po);
            }

            po.SetBPartner(vendor);

            // Code Commented by Vivek Kumar on 20/09/2017 Assigned By Pradeep  for drop shipment
            //	Drop Ship
            //po.SetIsDropShip(so.IsDropShip());
            //if (so.IsDropShip())
            //{
            //    po.SetShip_BPartner_ID(so.GetC_BPartner_ID());
            //    po.SetShip_Location_ID(so.GetC_BPartner_Location_ID());
            //    po.SetShip_User_ID(so.GetAD_User_ID());
            //}

            if (_shipDrop == "Y")
            {
                po.SetIsDropShip(true);
                po.SetShipToPartner_ID(so.GetC_BPartner_ID());
                po.SetShipToLocation_ID(so.GetC_BPartner_Location_ID());
                int _Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select M_WareHouse_ID From M_Warehouse Where AD_Org_ID=" + so.GetAD_Org_ID() + " AND Isdropship='Y' AND IsActive='Y'"));
                if (_Warehouse_ID >= 0)
                {
                    po.SetM_Warehouse_ID(_Warehouse_ID);
                }
            }

            // Added by Bharat on 29 Jan 2018 to set Inco Term from Order

            if (po.Get_ColumnIndex("C_IncoTerm_ID") > 0)
            {
                po.SetC_IncoTerm_ID(so.GetC_IncoTerm_ID());
            }
            //	References
            po.SetC_Activity_ID(so.GetC_Activity_ID());
            po.SetC_Campaign_ID(so.GetC_Campaign_ID());
            po.SetC_Project_ID(so.GetC_Project_ID());
            po.SetUser1_ID(so.GetUser1_ID());
            po.SetUser2_ID(so.GetUser2_ID());
            //
            po.Save();
            return(po);
        }
Exemple #12
0
        /// <summary>
        /// Generate Shipments
        /// </summary>
        /// <param name="idr">Order Query</param>
        /// <returns>info</returns>
        private String Generate(IDataReader idr)
        {
            DataTable dt     = new DataTable();
            MClient   client = MClient.Get(GetCtx());

            try
            {
                dt.Load(idr);
                idr.Close();
                //ResultSet dr = pstmt.executeQuery();
                foreach (DataRow dr in dt.Rows)//  while (dr.next ())		//	Order
                {
                    order = new MOrder(GetCtx(), dr, Get_TrxName());

                    // Credit Limit check added by Vivek on 24/08/2016
                    MBPartner bp = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                    if (bp.GetCreditStatusSettingOn() == "CH")
                    {
                        decimal creditLimit = bp.GetSO_CreditLimit();
                        string  creditVal   = bp.GetCreditValidation();
                        if (creditLimit != 0)
                        {
                            decimal creditAvlb = creditLimit - bp.GetSO_CreditUsed();
                            if (creditAvlb <= 0)
                            {
                                if (creditVal == "B" || creditVal == "D" || creditVal == "E" || creditVal == "F")
                                {
                                    AddLog(Msg.GetMsg(GetCtx(), "StopShipment") + bp.GetName());
                                    continue;
                                }
                                else if (creditVal == "H" || creditVal == "J" || creditVal == "K" || creditVal == "L")
                                {
                                    if (_msg != null)
                                    {
                                        _msg.Clear();
                                    }
                                    _msg.Append(Msg.GetMsg(GetCtx(), "WarningShipment") + bp.GetName());
                                    //AddLog(Msg.GetMsg(GetCtx(), "WarningShipment") + bp.GetName());
                                }
                            }
                        }
                    }
                    else
                    {
                        MBPartnerLocation bpl      = new MBPartnerLocation(GetCtx(), order.GetC_BPartner_Location_ID(), null);
                        MBPartner         bpartner = MBPartner.Get(GetCtx(), order.GetC_BPartner_ID());
                        if (bpl.GetCreditStatusSettingOn() == "CL")
                        {
                            decimal creditLimit = bpl.GetSO_CreditLimit();
                            string  creditVal   = bpl.GetCreditValidation();
                            if (creditLimit != 0)
                            {
                                decimal creditAvlb = creditLimit - bpl.GetSO_CreditUsed();
                                if (creditAvlb <= 0)
                                {
                                    if (creditVal == "B" || creditVal == "D" || creditVal == "E" || creditVal == "F")
                                    {
                                        AddLog(Msg.GetMsg(GetCtx(), "StopShipment") + bp.GetName() + " " + bpl.GetName());
                                        continue;
                                    }
                                    else if (creditVal == "H" || creditVal == "J" || creditVal == "K" || creditVal == "L")
                                    {
                                        if (_msg != null)
                                        {
                                            _msg.Clear();
                                        }
                                        _msg.Append(Msg.GetMsg(GetCtx(), "WarningShipment") + bp.GetName() + " " + bpl.GetName());
                                        //AddLog(Msg.GetMsg(GetCtx(), "WarningShipment") + bp.GetName() + " " + bpl.GetName());
                                    }
                                }
                            }
                        }
                    }
                    // Credit Limit End

                    //	New Header different Shipper, Shipment Location
                    if (!_consolidateDocument ||
                        (_shipment != null &&
                         (_shipment.GetC_BPartner_Location_ID() != order.GetC_BPartner_Location_ID() ||
                          _shipment.GetM_Shipper_ID() != order.GetM_Shipper_ID())))
                    {
                        CompleteShipment();
                    }
                    log.Fine("check: " + order + " - DeliveryRule=" + order.GetDeliveryRule());
                    //
                    DateTime?minGuaranteeDate = _movementDate;
                    bool     completeOrder    = MOrder.DELIVERYRULE_CompleteOrder.Equals(order.GetDeliveryRule());
                    //	OrderLine WHERE
                    String where = " AND M_Warehouse_ID=" + _M_Warehouse_ID;
                    if (_datePromised != null)
                    {
                        where += " AND (TRUNC(DatePromised,'DD')<=" + DB.TO_DATE((DateTime?)_datePromised, true)
                                 + " OR DatePromised IS NULL)";
                        //where += " AND (TRUNC(DatePromised,'DD')<='" + String.Format("{0:dd-MMM-yy}", _datePromised)
                        //    + "' OR DatePromised IS NULL)";
                    }
                    //	Exclude Auto Delivery if not Force
                    if (!MOrder.DELIVERYRULE_Force.Equals(order.GetDeliveryRule()))
                    {
                        where += " AND (C_OrderLine.M_Product_ID IS NULL"
                                 + " OR EXISTS (SELECT * FROM M_Product p "
                                 + "WHERE C_OrderLine.M_Product_ID=p.M_Product_ID"
                                 + " AND IsExcludeAutoDelivery='N'))";
                    }
                    //	Exclude Unconfirmed
                    if (!_isUnconfirmedInOut)
                    {
                        where += " AND NOT EXISTS (SELECT * FROM M_InOutLine iol"
                                 + " INNER JOIN M_InOut io ON (iol.M_InOut_ID=io.M_InOut_ID) "
                                 + "WHERE iol.C_OrderLine_ID=C_OrderLine.C_OrderLine_ID AND io.DocStatus IN ('IP','WC'))";
                    }
                    //	Deadlock Prevention - Order by M_Product_ID
                    MOrderLine[] lines = order.GetLines(where, "ORDER BY C_BPartner_Location_ID, M_Product_ID");
                    for (int i = 0; i < lines.Length; i++)
                    {
                        MOrderLine line = lines[i];
                        // if order line is not drop ship type
                        if (!line.IsDropShip())
                        {
                            if (line.GetM_Warehouse_ID() != _M_Warehouse_ID)
                            {
                                continue;
                            }
                            log.Fine("check: " + line);
                            Decimal onHand    = Env.ZERO;
                            Decimal toDeliver = Decimal.Subtract(line.GetQtyOrdered(),
                                                                 line.GetQtyDelivered());
                            Decimal QtyNotDelivered = Util.GetValueOfDecimal(DB.ExecuteScalar(@"SELECT SUM(MovementQty) FROM M_Inout i INNER JOIN M_InoutLine il ON i.M_Inout_ID = il.M_Inout_ID
                            WHERE il.C_OrderLine_ID = " + line.GetC_OrderLine_ID() + @" AND il.Isactive = 'Y' AND i.docstatus NOT IN ('RE' , 'VO' , 'CL' , 'CO')", null, Get_Trx()));
                            toDeliver -= QtyNotDelivered;
                            MProduct product = line.GetProduct();
                            //	Nothing to Deliver
                            if (product != null && Env.Signum(toDeliver) == 0)
                            {
                                continue;
                            }

                            // Added by Bharat on 07 April 2017 as code already on Admpiere but deleted here.
                            if (line.GetC_Charge_ID() != 0)
                            {
                                continue;
                            }

                            //	Check / adjust for confirmations
                            Decimal unconfirmedShippedQty = Env.ZERO;
                            if (_isUnconfirmedInOut && product != null && Env.Signum(toDeliver) != 0)
                            {
                                String       where2 = "EXISTS (SELECT * FROM M_InOut io WHERE io.M_InOut_ID=M_InOutLine.M_InOut_ID AND io.DocStatus IN ('IP','WC'))";
                                MInOutLine[] iols   = MInOutLine.GetOfOrderLine(GetCtx(),
                                                                                line.GetC_OrderLine_ID(), where2, null);
                                for (int j = 0; j < iols.Length; j++)
                                {
                                    unconfirmedShippedQty = Decimal.Add(unconfirmedShippedQty, iols[j].GetMovementQty());
                                }
                                String logInfo = "Unconfirmed Qty=" + unconfirmedShippedQty
                                                 + " - ToDeliver=" + toDeliver + "->";
                                toDeliver = Decimal.Subtract(toDeliver, unconfirmedShippedQty);
                                logInfo  += toDeliver;
                                if (Env.Signum(toDeliver) < 0)
                                {
                                    toDeliver = Env.ZERO;
                                    logInfo  += " (set to 0)";
                                }
                                //	Adjust On Hand
                                onHand = Decimal.Subtract(onHand, unconfirmedShippedQty);
                                log.Fine(logInfo);
                            }

                            //	Comments & lines w/o product & services
                            if ((product == null || !product.IsStocked()) &&
                                (Env.Signum(line.GetQtyOrdered()) == 0 ||                               //	comments
                                 Env.Signum(toDeliver) != 0))                                           //	lines w/o product
                            {
                                if (!MOrder.DELIVERYRULE_CompleteOrder.Equals(order.GetDeliveryRule())) //	printed later
                                {
                                    CreateLine(order, line, toDeliver, null, false);
                                }
                                continue;
                            }

                            //	Stored Product
                            MProductCategory pc       = MProductCategory.Get(order.GetCtx(), product.GetM_Product_Category_ID());
                            String           MMPolicy = pc.GetMMPolicy();
                            if (MMPolicy == null || MMPolicy.Length == 0)
                            {
                                MMPolicy = client.GetMMPolicy();
                            }
                            //
                            MStorage[] storages = GetStorages(line.GetM_Warehouse_ID(),
                                                              line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                              product.GetM_AttributeSet_ID(),
                                                              line.GetM_AttributeSetInstance_ID() == 0,
                                                              (DateTime?)minGuaranteeDate,
                                                              MClient.MMPOLICY_FiFo.Equals(MMPolicy));

                            for (int j = 0; j < storages.Length; j++)
                            {
                                MStorage storage = storages[j];
                                onHand = Decimal.Add(onHand, storage.GetQtyOnHand());
                            }
                            bool fullLine = onHand.CompareTo(toDeliver) >= 0 ||
                                            Env.Signum(toDeliver) < 0;

                            //	Complete Order
                            if (completeOrder && !fullLine)
                            {
                                log.Fine("Failed CompleteOrder - OnHand=" + onHand
                                         + " (Unconfirmed=" + unconfirmedShippedQty
                                         + "), ToDeliver=" + toDeliver + " - " + line);
                                completeOrder = false;
                                break;
                            }
                            //	Complete Line
                            else if (fullLine && MOrder.DELIVERYRULE_CompleteLine.Equals(order.GetDeliveryRule()))
                            {
                                log.Fine("CompleteLine - OnHand=" + onHand
                                         + " (Unconfirmed=" + unconfirmedShippedQty
                                         + ", ToDeliver=" + toDeliver + " - " + line);
                                //
                                CreateLine(order, line, toDeliver, storages, false);
                            }
                            //	Availability
                            else if (MOrder.DELIVERYRULE_Availability.Equals(order.GetDeliveryRule()) &&
                                     (Env.Signum(onHand) > 0 ||
                                      Env.Signum(toDeliver) < 0))
                            {
                                Decimal deliver = toDeliver;
                                if (deliver.CompareTo(onHand) > 0)
                                {
                                    deliver = onHand;
                                }
                                log.Fine("Available - OnHand=" + onHand
                                         + " (Unconfirmed=" + unconfirmedShippedQty
                                         + "), ToDeliver=" + toDeliver
                                         + ", Delivering=" + deliver + " - " + line);
                                //
                                CreateLine(order, line, deliver, storages, false);
                            }
                            //	Force
                            else if (MOrder.DELIVERYRULE_Force.Equals(order.GetDeliveryRule()))
                            {
                                Decimal deliver = toDeliver;
                                log.Fine("Force - OnHand=" + onHand
                                         + " (Unconfirmed=" + unconfirmedShippedQty
                                         + "), ToDeliver=" + toDeliver
                                         + ", Delivering=" + deliver + " - " + line);
                                //
                                CreateLine(order, line, deliver, storages, true);
                            }
                            //	Manual
                            else if (MOrder.DELIVERYRULE_Manual.Equals(order.GetDeliveryRule()))
                            {
                                log.Fine("Manual - OnHand=" + onHand
                                         + " (Unconfirmed=" + unconfirmedShippedQty
                                         + ") - " + line);
                            }
                            else
                            {
                                log.Fine("Failed: " + order.GetDeliveryRule() + " - OnHand=" + onHand
                                         + " (Unconfirmed=" + unconfirmedShippedQty
                                         + "), ToDeliver=" + toDeliver + " - " + line);
                            }
                        }
                    }//	for all order lines

                    //	Complete Order successful
                    if (completeOrder && MOrder.DELIVERYRULE_CompleteOrder.Equals(order.GetDeliveryRule()))
                    {
                        for (int i = 0; i < lines.Length; i++)
                        {
                            MOrderLine line = lines[i];
                            // if order line is not drop ship type
                            if (!line.IsDropShip())
                            {
                                if (line.GetM_Warehouse_ID() != _M_Warehouse_ID)
                                {
                                    continue;
                                }
                                MProduct product   = line.GetProduct();
                                Decimal  toDeliver = Decimal.Subtract(line.GetQtyOrdered(), line.GetQtyDelivered());
                                //
                                MStorage[] storages = null;
                                if (product != null && product.IsStocked())
                                {
                                    MProductCategory pc       = MProductCategory.Get(order.GetCtx(), product.GetM_Product_Category_ID());
                                    String           MMPolicy = pc.GetMMPolicy();
                                    if (MMPolicy == null || MMPolicy.Length == 0)
                                    {
                                        MMPolicy = client.GetMMPolicy();
                                    }
                                    //
                                    storages = GetStorages(line.GetM_Warehouse_ID(),
                                                           line.GetM_Product_ID(), line.GetM_AttributeSetInstance_ID(),
                                                           product.GetM_AttributeSet_ID(),
                                                           line.GetM_AttributeSetInstance_ID() == 0, (DateTime?)minGuaranteeDate,
                                                           MClient.MMPOLICY_FiFo.Equals(MMPolicy));
                                }
                                //
                                CreateLine(order, line, toDeliver, storages, false);
                            }
                        }
                    }
                    _line += 1000;
                }       //	while order
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, _sql, e);
            }
            finally
            {
                if (idr != null)
                {
                    idr.Close();
                }
                dt = null;
            }
            CompleteShipment();
            return("@Created@ = " + _created);
        }
        }       //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (text with variables)</returns>
        protected override String DoIt()
        {
            log.Info("C_BPartner_ID=" + _C_BPartner_ID
                     + ", AD_Org_ID=" + _AD_Org_ID
                     + ", AD_OrgType_ID=" + _AD_OrgType_ID
                     + ", AD_Role_ID=" + _AD_Role_ID);
            if (_C_BPartner_ID == 0)
            {
                throw new Exception("No Business Partner ID");
            }
            MBPartner bp = new MBPartner(GetCtx(), _C_BPartner_ID, Get_Trx());

            if (bp.Get_ID() == 0)
            {
                throw new Exception("Business Partner not found - C_BPartner_ID=" + _C_BPartner_ID);
            }
            //	BP Location
            MBPartnerLocation[] locs = bp.GetLocations(false);
            if (locs == null || locs.Length == 0)
            {
                throw new ArgumentException("Business Partner has no Location");
            }
            //	Location
            int C_Location_ID = locs[0].GetC_Location_ID();

            if (C_Location_ID == 0)
            {
                throw new ArgumentException("Business Partner Location has no Address");
            }

            //	Create Org
            Boolean newOrg = _AD_Org_ID == 0;
            MOrg    org    = new MOrg(GetCtx(), _AD_Org_ID, Get_Trx());

            if (newOrg)
            {
                org.SetValue(bp.GetValue());
                org.SetName(bp.GetName());
                org.SetDescription(bp.GetDescription());
                if (!org.Save())
                {
                    return(GetRetrievedError(org, "Organization not saved"));
                    //throw new Exception("Organization not saved");
                }
            }
            else        //	check if linked to already
            {
                int C_BPartner_ID = org.GetLinkedC_BPartner_ID();
                if (C_BPartner_ID > 0)
                {
                    throw new ArgumentException("Organization '" + org.GetName()
                                                + "' already linked (to C_BPartner_ID=" + C_BPartner_ID + ")");
                }
            }
            _AD_Org_ID = org.GetAD_Org_ID();

            //	Update Org Info
            MOrgInfo oInfo = org.GetInfo();

            oInfo.SetAD_OrgType_ID(_AD_OrgType_ID);
            if (newOrg)
            {
                oInfo.SetC_Location_ID(C_Location_ID);
            }

            //	Create Warehouse
            MWarehouse wh = null;

            if (!newOrg)
            {
                MWarehouse[] whs = MWarehouse.GetForOrg(GetCtx(), _AD_Org_ID);
                if (whs != null && whs.Length > 0)
                {
                    wh = whs[0]; //	pick first
                }
            }
            //	New Warehouse
            if (wh == null)
            {
                wh = new MWarehouse(org);
                if (!wh.Save())
                {
                    return(GetRetrievedError(wh, "Warehouse not saved"));
                    //throw new Exception("Warehouse not saved");
                }
            }
            //	Create Locator
            MLocator mLoc = wh.GetDefaultLocator();

            if (mLoc == null)
            {
                mLoc = new MLocator(wh, "Standard");
                mLoc.SetIsDefault(true);
                mLoc.Save();
            }

            //	Update/Save Org Info
            oInfo.SetM_Warehouse_ID(wh.GetM_Warehouse_ID());
            if (!oInfo.Save(Get_Trx()))
            {
                return(GetRetrievedError(oInfo, "Organization Info not saved"));
                //throw new Exception("Organization Info not saved");
            }

            //	Update BPartner
            bp.SetAD_OrgBP_ID(_AD_Org_ID);
            if (bp.GetAD_Org_ID() != 0)
            {
                bp.SetClientOrg(bp.GetAD_Client_ID(), 0); //	Shared BPartner
            }

            //	Save BP
            if (!bp.Save())
            {
                return(GetRetrievedError(bp, "Business Partner not updated"));
                //throw new Exception("Business Partner not updated");
            }

            //	Limit to specific Role
            if (_AD_Role_ID != 0)
            {
                Boolean          found       = false;
                MRoleOrgAccess[] orgAccesses = MRoleOrgAccess.GetOfOrg(GetCtx(), _AD_Org_ID);
                //	delete all accesses except the specific
                for (int i = 0; i < orgAccesses.Length; i++)
                {
                    if (orgAccesses[i].GetAD_Role_ID() == _AD_Role_ID)
                    {
                        found = true;
                    }
                    else
                    {
                        orgAccesses[i].Delete(true);
                    }
                }
                //	create access
                if (!found)
                {
                    MRoleOrgAccess orgAccess = new MRoleOrgAccess(org, _AD_Role_ID);
                    orgAccess.Save();
                }
            }

            //	Reset Client Role
            MRole.GetDefault(GetCtx(), true);

            return("Business Partner - Organization Link created");
        } //	doIt
Exemple #14
0
        /// <summary>
        /// Process
        /// </summary>
        /// <returns>info</returns>
        protected override String DoIt()
        {
            log.Info("C_DunningRun_ID=" + _C_DunningRun_ID + ",R_MailText_ID=" + _R_MailText_ID
                     + ", EmailPDF=" + _EMailPDF + ",IsOnlyIfBPBalance=" + _IsOnlyIfBPBalance);

            //	Need to have Template
            if (_EMailPDF && _R_MailText_ID == 0)
            {
                throw new Exception("@NotFound@: @R_MailText_ID@");
            }
            String    subject = "";
            MMailText mText   = null;

            if (_EMailPDF)
            {
                mText = new MMailText(GetCtx(), _R_MailText_ID, Get_TrxName());
                if (_EMailPDF && mText.Get_ID() == 0)
                {
                    throw new Exception("@NotFound@: @R_MailText_ID@ - " + _R_MailText_ID);
                }
                subject = mText.GetMailHeader();
            }
            //
            MDunningRun run = new MDunningRun(GetCtx(), _C_DunningRun_ID, Get_TrxName());

            if (run.Get_ID() == 0)
            {
                throw new Exception("@NotFound@: @C_DunningRun_ID@ - " + _C_DunningRun_ID);
            }
            //	Print Format on Dunning Level
            MDunningLevel level = new MDunningLevel(GetCtx(), run.GetC_DunningLevel_ID(), Get_TrxName());
            //MPrintFormat format = MPrintFormat.Get(GetCtx(), level.GetDunning_PrintFormat_ID(), false);

            MClient client = MClient.Get(GetCtx());

            int count  = 0;
            int errors = 0;

            MDunningRunEntry[] entries = run.GetEntries(false);
            for (int i = 0; i < entries.Length; i++)
            {
                MDunningRunEntry entry = entries[i];
                if (_IsOnlyIfBPBalance && Env.Signum(entry.GetAmt()) <= 0)
                {
                    continue;
                }
                //	To BPartner
                MBPartner bp = new MBPartner(GetCtx(), entry.GetC_BPartner_ID(), Get_TrxName());
                if (bp.Get_ID() == 0)
                {
                    AddLog(entry.Get_ID(), null, null, "@NotFound@: @C_BPartner_ID@ " + entry.GetC_BPartner_ID());
                    errors++;
                    continue;
                }
                //	To User
                MUser to = new MUser(GetCtx(), entry.GetAD_User_ID(), Get_TrxName());
                if (_EMailPDF)
                {
                    if (to.Get_ID() == 0)
                    {
                        AddLog(entry.Get_ID(), null, null, "@NotFound@: @AD_User_ID@ - " + bp.GetName());
                        errors++;
                        continue;
                    }
                    else if (to.GetEMail() == null || to.GetEMail().Length == 0)
                    {
                        AddLog(entry.Get_ID(), null, null, "@NotFound@: @EMail@ - " + to.GetName());
                        errors++;
                        continue;
                    }
                }
                //	BP Language
                //Language language =Language.getLoginLanguage();		//	Base Language
                Language language = Env.GetLoginLanguage(GetCtx());

                String tableName = "C_Dunning_Header_v";
                if (client.IsMultiLingualDocument())
                {
                    tableName += "t";
                    String AD_Language = bp.GetAD_Language();
                    if (AD_Language != null)
                    {
                        //language =language.getLanguage(AD_Language);
                    }
                }
                // format.SetLanguage(language);
                // format.SetTranslationLanguage(language);
                //	query
                Query query = new Query(tableName);
                query.AddRestriction("C_DunningRunEntry_ID", Query.EQUAL,
                                     entry.GetC_DunningRunEntry_ID());

                //	Engine
                //PrintInfo info = new PrintInfo(
                //    bp.GetName(),
                //    X_C_DunningRunEntry.Table_ID,
                //    entry.GetC_DunningRunEntry_ID(),
                //    entry.GetC_BPartner_ID());
                //info.SetDescription(bp.GetName() + ", Amt=" + entry.GetAmt());
                //ReportEngine re = new ReportEngine(GetCtx(), format, query, info);
                bool printed = false;
                if (_EMailPDF)
                {
                    EMail email = client.CreateEMail(to.GetEMail(), to.GetName(), null, null);
                    if (email == null || !email.IsValid())
                    {
                        AddLog(entry.Get_ID(), null, null,
                               "@RequestActionEMailError@ Invalid EMail: " + to);
                        errors++;
                        continue;
                    }
                    mText.SetUser(to);  //	variable context
                    mText.SetBPartner(bp);
                    mText.SetPO(entry);
                    String message = mText.GetMailText(true);
                    if (mText.IsHtml())
                    {
                        email.SetMessageHTML(mText.GetMailHeader(), message);
                    }
                    else
                    {
                        email.SetSubject(mText.GetMailHeader());
                        email.SetMessageText(message);
                    }
                    //
                    //File attachment = re.GetPDF(File.createTempFile("Dunning", ".pdf"));
                    //log.Fine(to + " - " + attachment);
                    //email.AddAttachment(attachment);
                    //
                    String    msg = email.Send();
                    MUserMail um  = new MUserMail(mText, entry.GetAD_User_ID(), email);
                    um.Save();
                    if (msg.Equals(EMail.SENT_OK))
                    {
                        AddLog(entry.Get_ID(), null, null,
                               bp.GetName() + " @RequestActionEMailOK@");
                        count++;
                        printed = true;
                    }
                    else
                    {
                        AddLog(entry.Get_ID(), null, null,
                               bp.GetName() + " @RequestActionEMailError@ " + msg);
                        errors++;
                    }
                }
                else
                {
                    //re.print();
                    count++;
                    printed = true;
                }
                if (printed)
                {
                    entry.SetProcessed(true);
                    entry.Save();
                    DunningLevelConsequences(level, entry);
                }
            }   //	for all dunning letters
            if (errors == 0)
            {
                run.SetProcessed(true);
                run.Save();
            }

            if (_EMailPDF)
            {
                return("@Sent@=" + count + " - @Errors@=" + errors);
            }
            return("@Printed@=" + count);
        }
Exemple #15
0
        /// <summary>
        /// Add Or Update Business Partner
        /// </summary>
        /// <param name="searchKey"></param>
        /// <param name="name"></param>
        /// <param name="name2"></param>
        /// <param name="greeting"></param>
        /// <param name="bpGroup"></param>
        /// <param name="bpRelation"></param>
        /// <param name="bpLocation"></param>
        /// <param name="contact"></param>
        /// <param name="greeting1"></param>
        /// <param name="title"></param>
        /// <param name="email"></param>
        /// <param name="address"></param>
        /// <param name="phoneNo"></param>
        /// <param name="phoneNo2"></param>
        /// <param name="fax"></param>
        /// <param name="ctx"></param>
        /// <param name="_windowNo"></param>
        /// <param name="BPtype"></param>
        /// <param name="C_BPartner_ID"></param>
        /// <returns></returns>

        public string AddBPartner(string searchKey, string name, string name2, string greeting, string bpGroup, string bpRelation, string bpLocation, string contact, string greeting1, string title, string email, string address, string phoneNo, string phoneNo2, string fax, Ctx ctx, int _windowNo, string BPtype, int C_BPartner_ID, bool isCustomer, bool isVendor, bool isProspect, string fileUrl, string umobile, string webUrl, bool isEmployee)
        {
            StringBuilder strError     = new StringBuilder();
            int           AD_Client_ID = ctx.GetAD_Client_ID();

            if (C_BPartner_ID > 0)
            {
                _partner = new MBPartner(ctx, C_BPartner_ID, null);
            }
            else
            {
                _partner = MBPartner.GetTemplate(ctx, AD_Client_ID);
            }
            bool isSOTrx = ctx.IsSOTrx(_windowNo);

            _partner.SetIsCustomer(isSOTrx);
            _partner.SetIsVendor(!isSOTrx);
            // JID_1197 IN Business partner  updating Createdby,Updatedby,Created,Updated fields as per changed date
            _partner.Set_ValueNoCheck("CreatedBy", ctx.GetAD_User_ID());
            _partner.Set_ValueNoCheck("Created", DateTime.Now);
            _partner.Set_ValueNoCheck("Updated", DateTime.Now);
            _partner.Set_ValueNoCheck("UpdatedBy", ctx.GetAD_User_ID());
            if (BPtype != null && (!isCustomer && !isVendor))
            {
                if (BPtype.Contains("Customer"))
                {
                    _partner.SetIsCustomer(true);
                }
                if (BPtype.Contains("Employee"))
                {
                    _partner.SetIsEmployee(true);
                }
                if (BPtype.Contains("Vendor"))
                {
                    _partner.SetIsVendor(true);
                }
                if (BPtype.Contains("Prospect"))
                {
                    _partner.SetIsProspect(true);
                }

                /*
                 * if (BPtype == "Customer")
                 * {
                 *  _partner.SetIsCustomer(true);
                 * }
                 * else if (BPtype == "Employee")
                 * {
                 *  _partner.SetIsEmployee(true);
                 * }
                 * else if (BPtype == "Vendor")
                 * {
                 *  _partner.SetIsVendor(true);
                 * }
                 * else if (BPtype == "Prospect")
                 * {
                 *  _partner.SetIsProspect(true);
                 * }*/
            }
            if (isCustomer)
            {
                _partner.SetIsCustomer(true);
            }
            else
            {
                _partner.SetIsCustomer(false);
            }
            if (isVendor)
            {
                _partner.SetIsVendor(true);
            }
            else
            {
                _partner.SetIsVendor(false);
            }
            if (isProspect)
            {
                _partner.SetIsProspect(true);
            }
            else
            {
                _partner.SetIsProspect(false);
            }

            if (isEmployee)
            {
                _partner.SetIsEmployee(true);
            }
            else
            {
                _partner.SetIsEmployee(false);
            }

            if (searchKey == null || searchKey.Length == 0)
            {
                //	get Table Documet No
                searchKey = MSequence.GetDocumentNo(ctx.GetAD_Client_ID(), "C_BPartner", null, ctx);
                //Dispatcher.BeginInvoke(() => { txtValue.Text = value; });
            }
            _partner.SetValue(searchKey);
            //
            _partner.SetName(name);
            _partner.SetURL(webUrl);
            //  _partner.SetName2(name2);
            //KeyNamePair p = (KeyNamePair)cmbGreetingBP.SelectedItem;
            //if (greeting >0)
            //{
            //    _partner.SetC_Greeting_ID(greeting);
            //}
            //else
            //{
            //    _partner.SetC_Greeting_ID(0);
            //}
            if (greeting != string.Empty)
            {
                _partner.SetC_Greeting_ID(Convert.ToInt32(greeting));
            }
            else
            {
                _partner.SetC_Greeting_ID(0);
            }
            /***************************************************/
            _partner.SetC_BP_Group_ID(Util.GetValueOfInt(bpGroup));
            /***************************************************/

            if (_partner.Save())
            {
                log.Fine("C_BPartner_ID=" + _partner.GetC_BPartner_ID());
            }
            else
            {
                // Classes.ShowMessage.Error("SearchKeyExist", null);
                strError.Append("SearchKeyExist");
                //this.Cursor = Cursors.Arrow;
                return(strError.ToString());
            }

            //	***** Business Partner - Location *****
            if (_pLocation == null)
            {
                if (C_BPartner_ID > 0)
                {
                    _pLocation = new MBPartnerLocation(ctx, GetBPartnerLocationID(_partner.Get_ID()), null);
                    if (_pLocation.Get_ID() <= 0)
                    {
                        _pLocation = new MBPartnerLocation(_partner);
                    }
                }
                else
                {
                    _pLocation = new MBPartnerLocation(_partner);
                }
            }
            if (address != string.Empty)
            {
                _pLocation.SetC_Location_ID(Convert.ToInt32(address));
            }

            //
            _pLocation.SetPhone(phoneNo);
            // _pLocation.SetPhone2(phoneNo2);
            _pLocation.SetFax(fax);
            if (_pLocation.Save())
            {
                log.Fine("C_BPartner_Location_ID=" + _pLocation.GetC_BPartner_Location_ID());
            }
            else
            {
                //   ADialog.error(m_WindowNo, this, "BPartnerNotSaved", Msg.translate(Env.getCtx(), "C_BPartner_Location_ID"));
                // Classes.ShowMessage.Error("BPartnerNotSaved", null);
                //this.Cursor = Cursors.Arrow;
                strError.Append("BPartnerNotSaved");
                return(strError.ToString());
            }

            //	***** Business Partner - User *****
            //String contact = txtContact.Text;
            //String email = txtEMail.Text;
            if (_user == null && (contact.Length > 0 || email.Length > 0))
            {
                if (C_BPartner_ID > 0)
                {
                    _user = new MUser(ctx, GetUserID(_partner.Get_ID()), null);
                }
                else
                {
                    _user = new MUser(_partner);
                }
            }
            if (_user != null)
            {
                if (contact.Length == 0)
                {
                    contact = name;
                }
                _user.SetName(contact);
                _user.SetEMail(email);
                _user.SetTitle(title);
                _user.SetC_Location_ID(Convert.ToInt32(address));

                // = (KeyNamePair)cmbGreetingC.SelectedItem;

                //if (greeting1 >0)
                //    _user.SetC_Greeting_ID(greeting1);
                if (greeting1 != string.Empty)
                {
                    _user.SetC_Greeting_ID(Convert.ToInt32(greeting1));
                }
                else
                {
                    _user.SetC_Greeting_ID(0);
                }
                //
                _user.SetPhone(phoneNo);
                // _user.SetPhone2(phoneNo2);
                _user.SetMobile(umobile);
                _user.SetFax(fax);
                _user.SetC_BPartner_Location_ID(_pLocation.GetC_BPartner_Location_ID());
                if (_user.Save())
                {
                    if (fileUrl != null && fileUrl != string.Empty)
                    {
                        _user.SetAD_Image_ID(SaveUserImage(ctx, fileUrl, _user.GetAD_User_ID()));
                    }
                    if (_user.Save())
                    {
                        log.Fine("AD_User_ID(AD_Image_ID)=" + _user.GetAD_User_ID() + "(" + _user.GetAD_Image_ID() + ")");
                    }
                    log.Fine("AD_User_ID=" + _user.GetAD_User_ID());
                }
                else
                {
                    //Classes.ShowMessage.Error("BPartnerNotSaved", null);
                    //this.Cursor = Cursors.Arrow;
                    strError.Append("BPartnerNotSaved");
                    return(strError.ToString());
                }

                /*************************************************/
                if ((bpRelation != null && bpLocation != null) && (bpRelation != string.Empty && bpLocation != string.Empty))
                {
                    if (bpRelation.ToString().Trim() == "" || bpLocation.ToString().Trim() == "")
                    {
                        int dele = DB.ExecuteQuery("DELETE from C_BP_Relation where c_bpartner_id=" + _partner.GetC_BPartner_ID(), null, null);
                        if (dele == -1)
                        {
                            log.SaveError("C_BP_RelationNotDeleted", "c_bpartner_id=" + _partner.GetC_BPartner_ID());
                        }
                    }
                    else
                    {
                        //Business Partner Relation
                        if (C_BPartner_ID > 0)
                        {
                            _bprelation = new X_C_BP_Relation(ctx, GetBPRelationID(_partner.Get_ID()), null);
                        }
                        else
                        {
                            _bprelation = new X_C_BP_Relation(ctx, 0, null);
                        }
                        _bprelation.SetAD_Client_ID(_partner.GetAD_Client_ID());
                        _bprelation.SetAD_Org_ID(_partner.GetAD_Org_ID());
                        _bprelation.SetName(_partner.GetName());
                        _bprelation.SetDescription(_partner.GetDescription());
                        _bprelation.SetC_BPartner_ID(_partner.GetC_BPartner_ID());
                        _bprelation.SetC_BPartner_Location_ID(_pLocation.GetC_BPartner_Location_ID());
                        _bprelation.SetC_BP_Relation_ID(Util.GetValueOfInt(bpRelation));
                        _bprelation.SetC_BPartnerRelation_ID(Util.GetValueOfInt(bpRelation));
                        _bprelation.SetC_BPartnerRelation_Location_ID(Util.GetValueOfInt(bpLocation));
                        _bprelation.SetIsBillTo(true);
                        if (_bprelation.Save())
                        {
                            log.Fine("C_BP_Relation_ID=" + _bprelation.GetC_BP_Relation_ID());
                        }
                        else
                        {
                            //Classes.ShowMessage.Error("BPRelationNotSaved", null);

                            //this.Cursor = Cursors.Arrow;
                            strError.Append("BPRelationNotSaved");
                            return(strError.ToString());
                        }
                    }
                }
                /*************************************************/
            }
            return(strError.ToString());
        }
        }       //	prepare

        /// <summary>
        /// Perform Process.
        /// </summary>
        /// <returns>Message (clear text)</returns>
        protected override String DoIt()
        {
            int           index = 1;
            StringBuilder sql   = new StringBuilder("SELECT * "
                                                    + "FROM S_TimeExpense e "
                                                    + "WHERE e.Processed='Y'"
                                                    + " AND e.AD_Client_ID=@param1"); //	#1

            if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1)
            {
                index++;
                sql.Append(" AND e.C_BPartner_ID=@param2");     //	#2
            }
            if (_DateFrom != null)
            {
                index++;
                sql.Append(" AND e.DateReport >=@param3");      //	#3
            }
            if (_DateTo != null)
            {
                index++;
                sql.Append(" AND e.DateReport <=@param4");      //	#4
            }
            // JID_0868
            // chanegs done by Bharat on 12 September 2018 to handle the case if invoice is created with an expense for the selected Business Partner
            sql.Append(" AND EXISTS (SELECT * FROM S_TimeExpenseLine el "
                       + "WHERE e.S_TimeExpense_ID=el.S_TimeExpense_ID"
                       + " AND el.C_InvoiceLine_ID IS NULL"
                       + " AND el.ConvertedAmt<>0) "
                       + "ORDER BY e.C_BPartner_ID, e.S_TimeExpense_ID");

            //
            int          old_BPartner_ID = -1;
            MInvoice     invoice         = null;
            MTimeExpense te = null;

            //
            //PreparedStatement pstmt = null;
            SqlParameter[] param = new SqlParameter[index];
            IDataReader    idr   = null;
            DataTable      dt    = null;

            try
            {
                //pstmt = DataBase.prepareStatement (sql.toString (), get_TrxName());
                int par = 0;
                //pstmt.setInt(par++, getAD_Client_ID());
                param[0] = new SqlParameter("@param1", GetAD_Client_ID());
                if (_C_BPartner_ID != 0 && _C_BPartner_ID != -1)
                {
                    par++;
                    //pstmt.setInt (par++, _C_BPartner_ID);
                    param[par] = new SqlParameter("@param2", _C_BPartner_ID);
                }
                if (_DateFrom != null)
                {
                    par++;
                    //pstmt.setTimestamp (par++, _DateFrom);
                    param[par] = new SqlParameter("@param3", _DateFrom);
                }
                if (_DateTo != null)
                {
                    par++;
                    //pstmt.setTimestamp (par++, _DateTo);
                    param[par] = new SqlParameter("@param4", _DateTo);
                }
                //ResultSet rs = pstmt.executeQuery ();
                idr = DataBase.DB.ExecuteReader(sql.ToString(), param, Get_TrxName());
                dt  = new DataTable();
                dt.Load(idr);
                idr.Close();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    //	********* Expense Line Loop
                    {
                        te = new MTimeExpense(GetCtx(), dr, Get_TrxName());

                        //	New BPartner - New Order
                        //
                        if (te.GetC_BPartner_ID() != old_BPartner_ID)
                        {
                            CompleteInvoice(invoice, te);
                            MBPartner bp = new MBPartner(GetCtx(), te.GetC_BPartner_ID(), Get_TrxName());

                            log.Info("New Invoice for " + bp);
                            invoice = new MInvoice(GetCtx(), 0, Get_TrxName());


                            invoice.SetBPartner(bp);
                            if (invoice.GetC_BPartner_Location_ID() == 0)
                            {
                                log.Log(Level.SEVERE, "No BP Location: " + bp);
                                AddLog(0, te.GetDateReport(),
                                       null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName());
                                invoice = null;
                                break;
                            }

                            // Siddheshwar: added a code to check for payment method if null
                            if (bp.GetVA009_PO_PaymentMethod_ID() <= 0)
                            {
                                paymethod = GetPaymentMethod(te);
                                if (paymethod <= 0)
                                {
                                    if (!noPayMethEmp.Contains(bp.GetC_BPartner_ID()))
                                    {
                                        noPayMethEmp.Add(bp.GetC_BPartner_ID());
                                        if (string.IsNullOrEmpty(bpNameNoPM))
                                        {
                                            bpNameNoPM = bp.GetName();
                                        }
                                        else
                                        {
                                            bpNameNoPM += bp.GetName() + ", ";
                                        }
                                        return(Msg.GetMsg(GetCtx(), "NoPayMethEmp") + bpNameNoPM);
                                    }
                                }
                                else
                                {
                                    invoice.SetVA009_PaymentMethod_ID(paymethod);
                                }
                            }
                            else
                            {
                                //JID_1783_1 if active paymentMethod not found ,then dont create the invoice.

                                if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID=" + bp.GetVA009_PO_PaymentMethod_ID(), null, Get_Trx())).Equals("Y"))
                                {
                                    invoice.SetVA009_PaymentMethod_ID(bp.GetVA009_PO_PaymentMethod_ID());
                                }
                                else
                                {
                                    return(Msg.GetMsg(GetCtx(), "IsActivePaymentMethodInv"));;
                                }
                            }

                            // Checking  payment term

                            if (bp.GetPO_PaymentTerm_ID() <= 0)
                            {
                                payterm = GetPaymentTerm(te);
                                if (payterm <= 0)
                                {
                                    if (!PayTermEmp.Contains(bp.GetC_BPartner_ID()))
                                    {
                                        PayTermEmp.Add(bp.GetC_BPartner_ID());
                                        if (string.IsNullOrEmpty(bpNamePT))
                                        {
                                            bpNamePT = bp.GetName();
                                        }
                                        else
                                        {
                                            bpNamePT += bp.GetName() + ", ";
                                        }
                                        return(Msg.GetMsg(GetCtx(), "NoPayTerm") + bpNamePT);
                                    }
                                }
                                else
                                {
                                    invoice.SetC_PaymentTerm_ID(payterm);
                                }
                            }
                            else
                            {
                                //JID_1783_1 if active paymentTerm not found ,then dont create the invoice.
                                if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM C_PaymentTerm WHERE C_PaymentTerm_ID=" + bp.GetPO_PaymentTerm_ID(), null, Get_Trx())).Equals("Y"))
                                {
                                    invoice.SetC_PaymentTerm_ID(bp.GetPO_PaymentTerm_ID());
                                }
                                else
                                {
                                    return(Msg.GetMsg(GetCtx(), "IsActivePaymentTermInv"));
                                }
                            }


                            invoice.SetIsExpenseInvoice(true); //added by arpit asked by Surya Sir on DEC 28,2015
                            invoice.SetClientOrg(te.GetAD_Client_ID(), te.GetAD_Org_ID());

                            //invoice.SetVA009_PaymentMethod_ID(bp.GetVA009_PO_PaymentMethod_ID());
                            // JID_0868
                            // chanegs done by Bharat on 12 September 2018 to set the document type where Expense Invoice checkbox is true.
                            // String qry = "SELECT C_DocType_ID FROM C_DocType "
                            //+ "WHERE AD_Client_ID=@param1 AND DocBaseType=@param2"
                            //+ " AND IsActive='Y' AND IsExpenseInvoice = 'Y' "
                            //+ "ORDER BY C_DocType_ID DESC ,   IsDefault DESC";
                            String qry = "SELECT C_DocType_ID FROM C_DocType "
                                         + "WHERE AD_Client_ID=" + GetAD_Client_ID() + @" AND DocBaseType='" + MDocBaseType.DOCBASETYPE_APINVOICE + @"'"
                                         + " AND IsActive='Y' AND IsExpenseInvoice = 'Y'  AND AD_Org_ID IN(0," + te.GetAD_Org_ID() + ") "
                                         + " ORDER BY AD_Org_ID Desc, C_DocType_ID DESC ,   IsDefault DESC";

                            //int C_DocType_ID = DB.GetSQLValue(null, qry, GetAD_Client_ID(), MDocBaseType.DOCBASETYPE_APINVOICE);
                            int C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar(qry));
                            if (C_DocType_ID <= 0)
                            {
                                log.Log(Level.SEVERE, "Not found for AC_Client_ID="
                                        + GetAD_Client_ID() + " - " + MDocBaseType.DOCBASETYPE_APINVOICE);
                                return(Msg.GetMsg(GetCtx(), "NoDocTypeExpInvoice"));
                            }
                            else
                            {
                                log.Fine(MDocBaseType.DOCBASETYPE_APINVOICE);
                            }
                            invoice.SetC_DocTypeTarget_ID(C_DocType_ID);
                            //invoice.SetC_DocTypeTarget_ID(MDocBaseType.DOCBASETYPE_APINVOICE);	//	API

                            //commented by Arpit on Jan 4,2015       Mentis issue no.   0000310
                            //invoice.SetDocumentNo(te.GetDocumentNo());
                            //

                            invoice.SetM_PriceList_ID(te.GetM_PriceList_ID());
                            invoice.SetSalesRep_ID(te.GetDoc_User_ID());
                            String descr = Msg.Translate(GetCtx(), "S_TimeExpense_ID")
                                           + ": " + te.GetDocumentNo() + " "
                                           + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport());
                            invoice.SetDescription(descr);
                            if (!invoice.Save())
                            {
                                return(GetRetrievedError(invoice, "Cannot save Invoice"));
                                // new Exception("Cannot save Invoice");
                            }
                            //added by arpit asked by Surya Sir on 29/12/2015*******
                            else
                            {
                                old_BPartner_ID = bp.GetC_BPartner_ID();
                            }
                            //end***************
                        }
                        // JID_0868
                        //Description include all document numbers which is come from Time And Expense Recording window to expense invoice in case of multiple records
                        else if (old_BPartner_ID > 0)
                        {
                            String descr = invoice.GetDescription() + "\n" + Msg.Translate(GetCtx(), "S_TimeExpense_ID")
                                           + ": " + te.GetDocumentNo() + " "
                                           + DisplayType.GetDateFormat(DisplayType.Date).Format(te.GetDateReport());
                            invoice.SetDescription(descr);
                        }
                        MTimeExpenseLine[] tel = te.GetLines(false);
                        for (int i = 0; i < tel.Length; i++)
                        {
                            MTimeExpenseLine line = tel[i];

                            //	Already Invoiced or nothing to be reimbursed
                            if (line.GetC_InvoiceLine_ID() != 0 ||
                                Env.ZERO.CompareTo(line.GetQtyReimbursed()) == 0 ||
                                Env.ZERO.CompareTo(line.GetPriceReimbursed()) == 0)
                            {
                                continue;
                            }
                            //	Update Header info
                            if (line.GetC_Activity_ID() != 0 && line.GetC_Activity_ID() != invoice.GetC_Activity_ID())
                            {
                                invoice.SetC_Activity_ID(line.GetC_Activity_ID());
                            }
                            if (line.GetC_Campaign_ID() != 0 && line.GetC_Campaign_ID() != invoice.GetC_Campaign_ID())
                            {
                                invoice.SetC_Campaign_ID(line.GetC_Campaign_ID());
                            }
                            if (line.GetC_Project_ID() != 0 && line.GetC_Project_ID() != invoice.GetC_Project_ID())
                            {
                                invoice.SetC_Project_ID(line.GetC_Project_ID());
                            }
                            if (!invoice.Save())
                            {
                                return(GetRetrievedError(invoice, "Cannot save Invoice"));
                                //new Exception("Cannot save Invoice");
                            }

                            //	Create OrderLine
                            MInvoiceLine il = new MInvoiceLine(invoice);
                            //
                            if (line.GetM_Product_ID() != 0)
                            {
                                il.SetM_Product_ID(line.GetM_Product_ID(), true);
                            }
                            //added by arpit asked by Surya Sir on 28/12/2015_____***************************
                            if (line.GetC_Charge_ID() != 0)
                            {
                                il.SetC_Charge_ID(line.GetC_Charge_ID());
                            }
                            //end here *****************************
                            il.SetQty(line.GetQtyReimbursed());     //	Entered/Invoiced
                            il.SetDescription(line.GetDescription());
                            //
                            il.SetC_Project_ID(line.GetC_Project_ID());
                            il.SetC_ProjectPhase_ID(line.GetC_ProjectPhase_ID());
                            il.SetC_ProjectTask_ID(line.GetC_ProjectTask_ID());
                            il.SetC_Activity_ID(line.GetC_Activity_ID());
                            il.SetC_Campaign_ID(line.GetC_Campaign_ID());
                            //
                            //	il.setPrice();	//	not really a list/limit price for reimbursements
                            il.SetPrice(line.GetPriceReimbursed()); //
                            il.SetC_UOM_ID(line.GetC_UOM_ID());

                            // JID_0868
                            // chanegs done by Bharat on 12 September 2018 to set the Amount in List price column.
                            il.SetPriceList(line.GetPriceReimbursed());
                            il.SetTax();
                            if (!il.Save())
                            {
                                return(GetRetrievedError(il, "Cannot save Invoice"));
                                //new Exception("Cannot save Invoice Line");
                            }
                            //	Update TEL
                            line.SetC_InvoiceLine_ID(il.GetC_InvoiceLine_ID());
                            line.SetIsInvoiced(true);
                            line.Save();
                        }   //	for all expense lines
                    }
                }
                else
                {
                    message = Msg.GetMsg(GetCtx(), "NoRecForInv");
                }
                //	********* Expense Line Loop
                dt = null;
                //dt.Clear();
            }
            catch (Exception e)
            {
                if (dt != null)
                {
                    dt = null;
                }
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, sql.ToString(), e);
            }
            finally
            {
                if (dt != null)
                {
                    dt = null;
                }
                if (idr != null)
                {
                    idr.Close();
                }
            }
            CompleteInvoice(invoice, te);
            //if (_noInvoices == 0)
            //{

            //    message = " @No Record Found for Invoice  Creation@";
            //}

            //Code for Showing Message when PaymentTerm is null
            if (!string.IsNullOrEmpty(bpNamePT))
            {
                message += Msg.GetMsg(GetCtx(), "NoPayTerm") + bpNamePT + "\n";
            }

            //code for showing Error Message when Invoice is not completed
            if (!string.IsNullOrEmpty(bpNameInvoice))
            {
                message += Msg.GetMsg(GetCtx(), "NoInvoiceCreated") + bpNameInvoice + "\n";
            }

            if (!string.IsNullOrEmpty(bpNameNoPM))
            {
                message = Msg.GetMsg(GetCtx(), "NoPayMethEmp") + bpNameNoPM + "\n";
            }
            if (_noInvoices > 0)
            {
                message += "" + _noInvoices + " " + Msg.GetMsg(GetCtx(), "VIS_InvGenerated");
            }

            //return "" + _noInvoices + " @Invoices Generated Successfully@";
            return(message);
        }   //	doIt
        /// <summary>
        /// Create PO for Vendor
        /// </summary>
        /// <param name="C_BPartner_ID">vendor</param>
        /// <param name="so">sales order</param>
        /// <returns>MOrder</returns>
        public MOrder CreatePOForVendor(int C_BPartner_ID, MOrder so, string _shipDrop)
        {
            MOrder po = new MOrder(GetCtx(), 0, Get_TrxName());

            po.SetClientOrg(so.GetAD_Client_ID(), so.GetAD_Org_ID());
            po.SetRef_Order_ID(so.GetC_Order_ID());
            po.SetIsSOTrx(false);
            // method edited to set unreleased document type for PO
            po.SetC_DocTypeTarget_ID(false);
            //
            po.SetDescription(so.GetDescription());
            po.SetPOReference(so.GetDocumentNo());
            po.SetPriorityRule(so.GetPriorityRule());
            po.SetSalesRep_ID(so.GetSalesRep_ID());
            // Code Commented by Vivek Kumar on 20/09/2017 Assigned By Pradeep for drop shipment
            //po.SetM_Warehouse_ID(so.GetM_Warehouse_ID());
            //	Set Vendor
            MBPartner vendor = new MBPartner(GetCtx(), C_BPartner_ID, Get_TrxName());

            if (Env.IsModuleInstalled("VA009_"))
            {
                // Set PO Payment Method from Vendor
                if (Util.GetValueOfInt(vendor.GetVA009_PO_PaymentMethod_ID()) > 0)
                {
                    po.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(vendor.GetVA009_PO_PaymentMethod_ID()));
                }
                else
                {
                    if (string.IsNullOrEmpty(messageErrorOrSetting.ToString()))
                    {
                        messageErrorOrSetting.Append(Msg.GetMsg(GetCtx(), "VIS_PaymentMethodNotDefined") + " : " + vendor.GetName());
                    }
                    else
                    {
                        messageErrorOrSetting.Append(" , " + Msg.GetMsg(GetCtx(), "VIS_PaymentMethodNotDefined") + " : " + vendor.GetName());
                    }
                    po = null;
                    return(po);
                }
            }

            //JID_1252: If Vendor do not have Po Pricelist bind. System should give message.
            if (vendor.GetPO_PriceList_ID() > 0)
            {
                po.SetM_PriceList_ID(vendor.GetPO_PriceList_ID());
            }
            else
            {
                if (string.IsNullOrEmpty(messageErrorOrSetting.ToString()))
                {
                    messageErrorOrSetting.Append(Msg.GetMsg(GetCtx(), "VIS_VendorPrcListNotDefine") + " : " + vendor.GetName());
                }
                else
                {
                    messageErrorOrSetting.Append(" , " + Msg.GetMsg(GetCtx(), "VIS_VendorPrcListNotDefine") + " : " + vendor.GetName());
                }
                po = null;
                return(po);
            }

            // JID_1262: If Payment Term is not bind BP, BP Group and No Default Payment Term. System do not create PO neither give message.
            if (vendor.GetPO_PaymentTerm_ID() > 0)
            {
                po.SetC_PaymentTerm_ID(vendor.GetPO_PaymentTerm_ID());
            }
            else
            {
                if (string.IsNullOrEmpty(messageErrorOrSetting.ToString()))
                {
                    messageErrorOrSetting.Append(Msg.GetMsg(GetCtx(), "VIS_VendorPaytemNotDefine") + " : " + vendor.GetName());
                }
                else
                {
                    messageErrorOrSetting.Append(" , " + Msg.GetMsg(GetCtx(), "VIS_VendorPaytemNotDefine") + " : " + vendor.GetName());
                }
                po = null;
                return(po);
            }

            po.SetBPartner(vendor);

            // Code Commented by Vivek Kumar on 20/09/2017 Assigned By Pradeep  for drop shipment
            //	Drop Ship
            //po.SetIsDropShip(so.IsDropShip());
            //if (so.IsDropShip())
            //{
            //    po.SetShip_BPartner_ID(so.GetC_BPartner_ID());
            //    po.SetShip_Location_ID(so.GetC_BPartner_Location_ID());
            //    po.SetShip_User_ID(so.GetAD_User_ID());
            //}

            if (_shipDrop == "Y")
            {
                po.SetIsDropShip(true);
                po.SetShipToPartner_ID(so.GetC_BPartner_ID());
                po.SetShipToLocation_ID(so.GetC_BPartner_Location_ID());
                int _Warehouse_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select M_WareHouse_ID From M_Warehouse Where AD_Org_ID=" + so.GetAD_Org_ID() + " AND Isdropship='Y' AND IsActive='Y'"));
                if (_Warehouse_ID >= 0)
                {
                    po.SetM_Warehouse_ID(_Warehouse_ID);
                }
            }

            // Added by Bharat on 29 Jan 2018 to set Inco Term from Order

            if (po.Get_ColumnIndex("C_IncoTerm_ID") > 0)
            {
                po.SetC_IncoTerm_ID(so.GetC_IncoTerm_ID());
            }
            //	References
            po.SetC_Activity_ID(so.GetC_Activity_ID());
            po.SetC_Campaign_ID(so.GetC_Campaign_ID());
            po.SetC_Project_ID(so.GetC_Project_ID());
            po.SetUser1_ID(so.GetUser1_ID());
            po.SetUser2_ID(so.GetUser2_ID());

            //Set VA077 values on header level
            if (Env.IsModuleInstalled("VA077_"))
            {
                //Get the org count of legal entity org
                string sql    = @"SELECT Count(AD_Org_ID) FROM AD_Org WHERE IsActive='Y' 
                           AND (IsProfitCenter ='Y' OR IsCostCenter ='Y') AND 
                           AD_Client_Id=" + so.GetAD_Client_ID() + @" AND LegalEntityOrg = " + so.GetAD_Org_ID();
                int    result = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                if (result > 0)
                {
                    po.SetVA077_IsLegalEntity(true);
                }
            }

            // Handle error done by rakesh kumar on 17/Mar/2021
            if (!po.Save())
            {
                ValueNamePair pp  = VLogger.RetrieveError();
                string        msg = string.Empty;
                if (pp != null)
                {
                    msg = pp.GetName();
                    //if GetName is Empty then it will check GetValue
                    if (string.IsNullOrEmpty(msg))
                    {
                        msg = Msg.GetMsg("", pp.GetValue());
                    }
                }
                if (string.IsNullOrEmpty(msg))
                {
                    msg = Msg.GetMsg(GetCtx(), "RecordNotSaved");
                }


                log.Info("CreatePOfromSO : Not Saved. Error Value : " + msg);
                AddLog(0, null, null, msg + " : @DocumentNo@ : " + so.GetDocumentNo());
            }
            return(po);
        }