public TabDetails SaveChanges(PaymentInputValues inputs)
        {
            if (CheckMandatory(inputs))
            {
                return(Save(inputs));
            }

            return(details);
        }
        public PaymentModel(Ctx _ctx, PaymentInputValues inputValues)
        {
            ctx = _ctx;
            // values = inputValues.values;

            // values = JsonConvert.DeserializeObject<List<string>>(inputValues.values.ToString());

            _isSOTrx          = inputValues._isSOTrx;
            _DocStatus        = inputValues._DocStatus;
            _PaymentRule      = inputValues._PaymentRule;
            _C_Currency_ID    = inputValues._C_Currency_ID;
            _DateAcct         = Convert.ToDateTime(inputValues._DateAcct);
            _C_PaymentTerm_ID = inputValues._C_PaymentTerm_ID;
            _C_Payment_ID     = inputValues._C_Payment_ID;
            _AD_Client_ID     = inputValues._AD_Client_ID;
            _AD_Org_ID        = inputValues._AD_Org_ID;
            _C_BPartner_ID    = inputValues._C_BPartner_ID;
            _Amount           = inputValues._Amount;
            _C_CashLine_ID    = inputValues._C_CashLine_ID;
        }
        /// <summary>
        /// Check Mandatory
        /// </summary>
        /// <returns>true if all mandatory items are OK</returns>
        private bool CheckMandatory(PaymentInputValues inputs)
        {
            if (details == null)
            {
                details = new TabDetails();
            }
            bool          dataOK = true;
            StringBuilder msg    = new StringBuilder();

            try
            {
                //	log.config( "VPayment.checkMandatory");

                String PaymentRule = inputs.cmbPayment;
                if (PaymentRule == null)
                {
                    return(false);
                }
                //  only Payment Rule
                if (inputs.OnlyRule)
                {
                    return(true);
                }

                DateTime?DateAcct         = inputs._DateAcct;
                int      C_PaymentTerm_ID = inputs._C_PaymentTerm_ID;
                int      C_CashBook_ID    = inputs._C_CashBook_ID;
                String   CCType           = inputs.CCType;
                //
                int C_BankAccount_ID = 0;

                /***********************
                 *	Mandatory Data Check
                 */

                //	B (Cash)		(Currency)
                if (PaymentRule.Equals(MOrder.PAYMENTRULE_Cash))
                {
                    C_CashBook_ID = inputs.cmbBCashBook;
                    DateAcct      = Convert.ToDateTime(inputs.bDateField);
                }

                //	K (CreditCard)  Type, Number, Exp, Approval
                else if (PaymentRule.Equals(MOrder.PAYMENTRULE_CreditCard))
                {
                    CCType = inputs.cmbKType;
                    //
                    String error = MPaymentValidate.ValidateCreditCardNumber(inputs.txtKNumber, CCType);
                    if (error.Length != 0)
                    {
                        //txtKNumber.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        if (error.IndexOf("?") == -1)
                        {
                            msg.Append(Msg.GetMsg(ctx, error) + Environment.NewLine);
                            //  ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                            dataOK = false;
                        }
                        else    //  warning
                        {
                            //if (!ShowMessage.Ask("", true, error))
                            //{
                            dataOK = false;
                            //}
                        }
                    }
                    error = MPaymentValidate.ValidateCreditCardExp(inputs.txtKExp);
                    if (error.Length != 0)
                    {
                        //txtKExp.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        msg.Append(Msg.GetMsg(ctx, error) + Environment.NewLine);
                        //ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                }

                //	T (Transfer)	BPartner_Bank
                else if (PaymentRule.Equals(X_C_Order.PAYMENTRULE_DirectDeposit) ||
                         PaymentRule.Equals(X_C_Order.PAYMENTRULE_DirectDebit))
                {
                    string bpba = inputs.cmbTAccount;
                    if (bpba == null || bpba == "")
                    {
                        msg.Append(Msg.GetMsg(ctx, "PaymentBPBankNotFound") + Environment.NewLine);
                        //   details.ErrorMsg = Msg.GetMsg(ctx, "PaymentBPBankNotFound");
                        //cmbTAccount.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        //ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentBPBankNotFound", true).ToString());
                        dataOK = false;
                    }
                }       //	Direct

                //	P (PaymentTerm)	PaymentTerm
                else if (PaymentRule.Equals(X_C_Order.PAYMENTRULE_OnCredit))
                {
                    C_PaymentTerm_ID = inputs.cmbPTerm;
                }

                //	S (Check)		(Currency) CheckNo, Routing
                else if (PaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                {
                    //	cmbSCurrency.SelectedItem;
                    C_BankAccount_ID = inputs.cmbSBankAccount;

                    String error = MPaymentValidate.ValidateRoutingNo(inputs.txtSRouting);
                    if (error.Length != 0)
                    {
                        msg.Append(Msg.GetMsg(ctx, error) + Environment.NewLine);
                        //    txtSRouting.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        //   ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                    error = MPaymentValidate.ValidateAccountNo(inputs.txtSNumber);
                    if (error.Length != 0)
                    {
                        msg.Append(Msg.GetMsg(ctx, error) + Environment.NewLine);
                        // txtSNumber.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        // ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                    error = MPaymentValidate.ValidateCheckNo(inputs.txtSCheck);
                    if (error.Length != 0)
                    {
                        msg.Append(Msg.GetMsg(ctx, error) + Environment.NewLine);
                        // txtSCheck.Background = new SolidColorBrush(GlobalVariable.MANDATORY_TEXT_BACK_COLOR);
                        // ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), error, true).ToString());
                        dataOK = false;
                    }
                }
                else
                {
                    //log.Log(Level.SEVERE, "Unknown PaymentRule " + PaymentRule);
                    return(false);
                }

                //  find Bank Account if not qualified yet
                if ("KTSD".IndexOf(PaymentRule) != -1 && C_BankAccount_ID == 0)
                {
                    String tender = MPayment.TENDERTYPE_CreditCard;
                    if (PaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDeposit;
                    }
                    else if (PaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDebit;
                    }
                    else if (PaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        tender = MPayment.TENDERTYPE_Check;
                    }
                    //	Check must have a bank account
                    if (C_BankAccount_ID == 0 && "S".Equals(PaymentRule))
                    {
                        msg.Append(Msg.GetMsg(ctx, "PaymentNoProcessor") + Environment.NewLine);
                        //  ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "PaymentNoProcessor", true).ToString());
                        dataOK = false;
                    }
                }
            }
            catch (Exception ex)
            {
                msg.Append(Msg.GetMsg(ctx, ex.Message) + Environment.NewLine);
                //    log.Severe(ex.ToString());
            }
            //log.Config("OK=" + dataOK);
            details.ErrorMsg = msg.ToString();
            return(dataOK);
        }
        private TabDetails Save(PaymentInputValues inputs)
        {
            try
            {
                StringBuilder errorMsg       = new StringBuilder();
                string        SucessMsg      = "";
                String        newPaymentRule = inputs.cmbPayment;
                inputs._DateAcct = Convert.ToDateTime(inputs._DateAcct);
                DateTime?newDateAcct         = Convert.ToDateTime(inputs._DateAcct);
                int      newC_PaymentTerm_ID = inputs._C_PaymentTerm_ID;
                int      newC_CashLine_ID    = inputs._C_CashLine_ID;
                int      newC_CashBook_ID    = inputs._C_CashBook_ID;
                String   newCCType           = inputs.CCType;
                int      newC_BankAccount_ID = 0;

                //	B (Cash)		(Currency)
                if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                {
                    newC_CashBook_ID = inputs.cmbBCashBook;
                    //newDateAcct = (DateTime)bDateField.GetValue();
                    newDateAcct = Convert.ToDateTime(inputs.bDateField);
                }

                //	K (CreditCard)  Type, Number, Exp, Approval
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_CreditCard))
                {
                    newCCType = inputs.cmbKType;
                }

                //	T (Transfer)	BPartner_Bank
                else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit) ||
                         newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                {
                    // KeyNamePair myObj = (KeyNamePair)cmbTAccount.SelectedItem;
                }

                //	P (PaymentTerm)	PaymentTerm
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_OnCredit))
                {
                    newC_PaymentTerm_ID = inputs.cmbPTerm;
                }

                //	S (Check)		(Currency) CheckNo, Routing
                else if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Check))
                {
                    //	cmbSCurrency.SelectedItem;
                    newC_BankAccount_ID = inputs.cmbSBankAccount;
                }
                else
                {
                    return(details);
                }


                SetPayments(inputs._C_Payment_ID, inputs._C_Currency_ID, inputs._PaymentRule);


                //  find Bank Account if not qualified yet
                if ("KTSD".IndexOf(newPaymentRule) != -1 && newC_BankAccount_ID == 0)
                {
                    String tender = MPayment.TENDERTYPE_CreditCard;
                    if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDeposit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDeposit;
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_DirectDebit))
                    {
                        tender = MPayment.TENDERTYPE_DirectDebit;
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        tender = MPayment.TENDERTYPE_Check;
                    }
                }

                /***********************
                 *  Changed PaymentRule
                 */
                if (!newPaymentRule.Equals(inputs._PaymentRule))
                {
                    //log.fine("Changed PaymentRule: " + _PaymentRule + " -> " + newPaymentRule);
                    //  We had a CashBook Entry
                    if (inputs._PaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                    {
                        //log.fine("Old Cash - " + _cashLine);
                        if (_cashLine != null)
                        {
                            MCashLine cl = _cashLine.CreateReversal();
                            if (cl.Save())
                            {
                                // log.Config("CashCancelled");
                            }
                            else
                            {
                                errorMsg.Append(Msg.GetMsg(ctx, "CashNotCancelled", true) + Environment.NewLine);
                                //   ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "CashNotCancelled", true).ToString());
                            }
                        }
                        newC_CashLine_ID = 0;      //  reset
                    }
                    //  We had a change in Payment type (e.g. Check to CC)
                    else if ("KTSD".IndexOf(_PaymentRule) != -1 && "KTSD".IndexOf(newPaymentRule) != -1 && _mPaymentOriginal != null)
                    {
                        //log.fine("Old Payment(1) - " + _mPaymentOriginal);
                        _mPaymentOriginal.SetDocAction(DocActionVariables.ACTION_REVERSE_CORRECT);
                        bool ok = _mPaymentOriginal.ProcessIt(DocActionVariables.ACTION_REVERSE_CORRECT);
                        _mPaymentOriginal.Save();
                        if (ok)
                        {
                            // log.Info("Payment Canecelled - " + _mPaymentOriginal);
                        }
                        else
                        {
                            errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "PaymentNotCancelled", true) + Environment.NewLine);
                            // ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCancelled", true).ToString() + _mPaymentOriginal.GetDocumentNo());
                        }
                        _mPayment.ReSetNew();
                    }
                    //	We had a Payment and something else (e.g. Check to Cash)
                    else if ("KTSD".IndexOf(_PaymentRule) != -1 && "KTSD".IndexOf(newPaymentRule) == -1)
                    {
                        //log.fine("Old Payment(2) - " + _mPaymentOriginal);
                        if (_mPaymentOriginal != null)
                        {
                            _mPaymentOriginal.SetDocAction(DocActionVariables.ACTION_REVERSE_CORRECT);
                            bool ok = _mPaymentOriginal.ProcessIt(DocActionVariables.ACTION_REVERSE_CORRECT);
                            _mPaymentOriginal.Save();
                            if (ok)        //  Cancel Payment
                            {
                                ///log.Fine("PaymentCancelled " + _mPayment.GetDocumentNo());
                                //_mTab.getTableModel().dataSave(true);
                                // DataRow datarow = null;
                                // _mTab.GetTableObj().DataSave(true, datarow);//**********************************2nd parameter
                                _mPayment.ReSetNew();
                                _mPayment.SetAmount(inputs._C_Currency_ID, inputs._Amount);
                            }
                            else
                            {
                                errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "PaymentNotCancelled", true) + _mPayment.GetDocumentNo() + Environment.NewLine);
                                //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCancelled", true).ToString() + _mPayment.GetDocumentNo());
                            }
                        }
                    }
                }


                //  Get Order and optionally Invoice
                //int C_Order_ID = ctx.GetContextAsInt(inputs.WindowNo, "C_Order_ID");
                //int C_Invoice_ID = ctx.GetContextAsInt(inputs.WindowNo, "C_Invoice_ID");
                if (inputs.C_Invoice_ID == 0 && inputs._DocStatus.Equals("CO"))
                {
                    inputs.C_Invoice_ID = GetInvoiceID(inputs.C_Order_ID);
                }
                //  Amount sign negative, if ARC (Credit Memo) or API (AP Invoice)
                bool     negateAmt = false;
                MInvoice invoice   = null;
                if (inputs.C_Invoice_ID != 0)
                {
                    invoice   = new MInvoice(ctx, inputs.C_Invoice_ID, null);
                    negateAmt = invoice.IsCreditMemo();
                }
                MOrder order = null;
                if (invoice == null && inputs.C_Order_ID != 0)
                {
                    order = new MOrder(ctx, inputs.C_Order_ID, null);
                }
                Decimal payAmount = inputs._Amount;
                if (negateAmt)
                {
                    payAmount = Decimal.Negate(inputs._Amount);//.negate();
                }
                // Info
                //    log.Config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt);


                /***********************
                 *  CashBook
                 */
                if (newPaymentRule.Equals(X_C_Order.PAYMENTRULE_Cash))
                {
                    //log.fine("Cash");
                    String description = inputs.Description;

                    if (inputs.C_Invoice_ID == 0 && order == null)
                    {
                        //log.Config("No Invoice!");
                        //     ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                        errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCreated", true) + Environment.NewLine);
                    }
                    else
                    {
                        //  Changed Amount
                        if (inputs._C_CashLine_ID > 0)
                        {
                            _cashLine = new MCashLine(ctx, inputs._C_CashLine_ID, null);
                        }


                        if (_cashLine != null &&
                            payAmount.CompareTo(_cashLine.GetAmount()) != 0)
                        {
                            // log.Config("Changed CashBook Amount");
                            _cashLine.SetAmount(payAmount);
                            if (_cashLine.Save())
                            {
                                //     log.Config("CashAmt Changed");
                            }
                        }
                        //	Different Date/CashBook
                        if (_cashLine != null &&
                            (newC_CashBook_ID != inputs._C_CashBook_ID ||
                             !TimeUtil.IsSameDay(_cashLine.GetStatementDate(), newDateAcct)))
                        {
                            //log.Config("Changed CashBook/Date: " + _C_CashBook_ID + "->" + newC_CashBook_ID);
                            MCashLine reverse = _cashLine.CreateReversal();
                            if (!reverse.Save())
                            {
                                errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCancelled", true) + Environment.NewLine);
                                //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCancelled", true).ToString());
                            }
                            _cashLine = null;
                        }

                        //	Create new
                        if (_cashLine == null)
                        {
                            // log.Config("New CashBook");
                            int C_Currency_ID = 0;
                            if (invoice != null)
                            {
                                C_Currency_ID = invoice.GetC_Currency_ID();
                            }
                            if (C_Currency_ID == 0 && order != null)
                            {
                                C_Currency_ID = order.GetC_Currency_ID();
                            }
                            MCash cash = null;
                            if (newC_CashBook_ID != 0)
                            {
                                cash = MCash.Get(ctx, newC_CashBook_ID, newDateAcct, null);
                            }
                            else        //	Default
                            {
                                cash = MCash.Get(ctx, inputs._AD_Org_ID, newDateAcct, C_Currency_ID, null);
                            }
                            if (cash == null || cash.Get_ID() == 0)
                            {
                                errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCreated", true) + Environment.NewLine);
                                //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                            }
                            else
                            {
                                MCashLine cl = new MCashLine(cash);
                                if (invoice != null)
                                {
                                    cl.SetInvoice(invoice);
                                }
                                if (order != null)
                                {
                                    cl.SetOrder(order, null);
                                    //_needSave = true;
                                }
                                if (cl.Save())
                                {
                                    //log.Config("CashCreated");
                                }
                                else
                                {
                                    errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "CashNotCreated", true) + Environment.NewLine);
                                    //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "CashNotCreated", true).ToString());
                                }
                            }
                        }
                    }   //	have invoice
                }

                /***********************
                 *  Payments
                 */
                if ("KS".IndexOf(newPaymentRule) != -1)
                {
                    //log.fine("Payment - " + newPaymentRule);
                    //  Set Amount
                    _mPayment.SetAmount(inputs._C_Currency_ID, payAmount);
                    if (newPaymentRule.Equals(MOrder.PAYMENTRULE_CreditCard))
                    {
                        _mPayment.SetCreditCard(MPayment.TRXTYPE_Sales, newCCType,
                                                inputs.txtKNumber, "", inputs.txtKExp);
                        _mPayment.SetPaymentProcessor();
                    }
                    else if (newPaymentRule.Equals(MOrder.PAYMENTRULE_Check))
                    {
                        _mPayment.SetBankCheck(newC_BankAccount_ID, inputs._isSOTrx, inputs.txtSRouting,
                                               inputs.txtSNumber, inputs.txtSCheck);
                    }
                    _mPayment.SetC_BPartner_ID(inputs._C_BPartner_ID);
                    _mPayment.SetC_Invoice_ID(inputs.C_Invoice_ID);
                    if (order != null)
                    {
                        _mPayment.SetC_Order_ID(inputs.C_Order_ID);
                        //     _needSave = true;
                    }
                    _mPayment.SetDateTrx(DateTime.SpecifyKind(Convert.ToDateTime(inputs._DateAcct), DateTimeKind.Utc));
                    _mPayment.SetDateAcct(DateTime.SpecifyKind(Convert.ToDateTime(inputs._DateAcct), DateTimeKind.Utc));
                    _mPayment.Save();

                    //  Save/Post
                    if (MPayment.DOCSTATUS_Drafted.Equals(_mPayment.GetDocStatus()))
                    {
                        bool ok = _mPayment.ProcessIt(DocActionVariables.ACTION_COMPLETE);
                        _mPayment.Save();
                        if (ok)
                        {
                            SucessMsg = _mPayment.GetDocumentNo().ToString() + Msg.GetMsg(ctx, "PaymentCreated");
                            //ShowMessage.Info(_mPayment.GetDocumentNo().ToString(), true, "PaymentCreated", "");
                        }
                        else
                        {
                            errorMsg.Append("PaymentError---" + Msg.GetMsg(ctx, "PaymentNotCreated", true) + Environment.NewLine);
                            //ShowMessage.Error("", true, "PaymentError" + Msg.GetMsg(Envs.GetContext(), "PaymentNotCreated", true).ToString());
                        }
                    }
                    else
                    {
                        // log.Fine("NotDraft " + _mPayment);
                    }
                }
                if (details == null)
                {
                    details = new TabDetails();
                }
                details.newPaymentRule      = newPaymentRule;
                details.newDateAcct         = newDateAcct;
                details._C_CashLine_ID      = inputs._C_CashLine_ID;
                details._C_Payment_ID       = inputs._C_Payment_ID;
                details.newC_PaymentTerm_ID = inputs.cmbPTerm;
                details.ErrorMsg            = errorMsg.ToString();
                details.SucessMsg           = SucessMsg;
            }
            catch
            {
            }
            return(details);
        }