public ReceiptInvoice CreateFakeInvoice(PO po,int IDPrinted,int userID)
        {
            ReceiptInvoice rctInvoice = new ReceiptInvoice();
            rctInvoice.AddNew();

            //Enter Invoice Related Information
            //We should Save the STV Number Here
            rctInvoice.POID = po.ID;

            rctInvoice.SavedByUserID = userID;
            rctInvoice.ActivityID = po.StoreID;

            rctInvoice.STVOrInvoiceNo = IDPrinted.ToString("00000");
            rctInvoice.ExchangeRate = 1;
            rctInvoice.Insurance = 0;
            rctInvoice.InvoiceTypeID = InvoiceType.Internal;
            rctInvoice.DateOfEntry = DateTimeHelper.ServerDateTime;
            rctInvoice.ActivityID = po.StoreID;
            rctInvoice.SavedByUserID = CurrentContext.LoggedInUser.ID;
            rctInvoice.IsDeliveryNote = false;
            rctInvoice.Rowguid = Guid.NewGuid();
            rctInvoice.PrintedDate = DateTime.Now;
            rctInvoice.IsVoided = false;
            rctInvoice.ShippingSite = " ";
            rctInvoice.IsConvertedFromDeliveryNote = false;
            rctInvoice.Save();
            return rctInvoice;
        }
Beispiel #2
0
 public static PO insertPO(APCEntities APCContext, Supplier supplier, Project project)
 {
     PO po = new PO();
     po.Supplier = supplier;
     po.Project = project;
     po.DateCreated = DateTime.Today;
     po.Invoiced = false;
     APCContext.AddToPO(po);
     APCContext.SaveChanges();
     return po;
 }
Beispiel #3
0
 public static bool insertPO_Product(APCEntities APCContext, PO po, Category category, string description, int quantity, decimal price, decimal serviceCharge, decimal totalPrice, bool subcon)
 {
     PO_Product po_product = new PO_Product();
     po_product.PO = po;
     po_product.Category = category;
     po_product.Description = description;
     po_product.Quantity = quantity;
     po_product.Price = price;
     po_product.ServiceCharge = serviceCharge;
     po_product.PriceTotal = totalPrice;
     po_product.SubCon = subcon;
     APCContext.AddToPO_Product(po_product);
     APCContext.SaveChanges();
     return true;
 }
Beispiel #4
0
 /// <summary>
 /// There are no comments for PO in the schema.
 /// </summary>
 public void AddToPO(PO pO)
 {
     base.AddObject("PO", pO);
 }
Beispiel #5
0
        private void SetBaseInfo(PO entity)
        {
            StockName = entity.StockName;
            ETATime   = entity.ETATime.ToLongTimeString();
            switch (entity.StockSysNo)
            {
            case 50:
                switch (entity.ITStockSysNo)
                {
                case 52:
                    StockName = "经中转到北京仓";
                    break;

                case 53:
                    StockName = "经中转到广州仓";
                    break;

                case 54:
                    StockName = "经中转到成都仓";
                    break;

                case 55:
                    StockName = "经中转到武汉仓";
                    break;

                case 56:
                    StockName = "经中转到西安仓";
                    break;

                case 57:
                    StockName = "经中转到济南仓";
                    break;

                case 58:
                    StockName = "经中转到南京仓";
                    break;
                }
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddress;
                CompanyTel     = NeweggConfig.Default.CompanyTel;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSite;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemo;
                break;

            case 51:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddress;
                CompanyTel     = NeweggConfig.Default.CompanyTel;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSite;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemo;
                break;

            case 52:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddressBJ;
                CompanyTel     = NeweggConfig.Default.CompanyTelBJ;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSiteBJ;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemoBJ;
                break;

            case 53:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddressGZ;
                CompanyTel     = NeweggConfig.Default.CompanyTelGZ;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSiteGZ;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemoGZ;
                break;

            case 54:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddressCD;
                CompanyTel     = NeweggConfig.Default.CompanyTelCD;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSiteCD;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemoGZ;
                break;

            case 55:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddressWH;
                CompanyTel     = NeweggConfig.Default.CompanyTelWH;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSiteWH;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemoGZ;
                break;

            case 59:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddressMH;
                CompanyTel     = NeweggConfig.Default.CompanyTelMH;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSiteMH;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemoGZ;
                break;

            default:
                CompanyName    = NeweggConfig.Default.CompanyName;
                CompanyAddress = NeweggConfig.Default.CompanyAddress;
                CompanyTel     = NeweggConfig.Default.CompanyTel;
                CompanyWebSite = NeweggConfig.Default.CompanyWebSite;
                StockAddress   = entity.ReceiveAddress;
                StockContact   = entity.ReceiveContact;
                StockTel       = entity.ReceiveContactPhone;
                VendorMemo     = NeweggConfig.Default.VendorMemo;
                break;
            }
        }
Beispiel #6
0
 public static bool insertInvoicePO(APCEntities APCContext, Invoice invoice, PO po)
 {
     try
     {
         Invoice_PO invoicePO = new Invoice_PO();
         invoicePO.Invoice = invoice;
         invoicePO.PO = po;
         APCContext.AddToInvoice_PO(invoicePO);
         po.Invoiced = true;
         APCContext.SaveChanges();
         return true;
     }
     catch(Exception e)
     {
         return false;
     }
 }
Beispiel #7
0
        protected override void OnToolGUI(Event e)
        {
            if (UIView.HasModalInput() || UIView.HasInputFocus())
            {
                return;
            }

            lock (ActionQueue.instance)
            {
                if (ToolState == ToolStates.Default)
                {
                    if (OptionsKeymapping.undo.IsPressed(e))
                    {
                        m_nextAction = ToolAction.Undo;
                    }
                    else if (OptionsKeymapping.redo.IsPressed(e))
                    {
                        m_nextAction = ToolAction.Redo;
                    }
                }

                if (OptionsKeymapping.copy.IsPressed(e))
                {
                    if (ToolState == ToolStates.Cloning || ToolState == ToolStates.RightDraggingClone)
                    {
                        StopCloning();
                    }
                    else
                    {
                        StartCloning();
                    }
                }
                //else if (OptionsKeymapping.testKey.IsPressed(e))
                //{ }
                else if (OptionsKeymapping.bulldoze.IsPressed(e))
                {
                    StartBulldoze();
                }
                else if (OptionsKeymapping.viewGrid.IsPressed(e))
                {
                    if (gridVisible)
                    {
                        gridVisible = false;
                        UIToolOptionPanel.instance.grid.activeStateIndex = 0;
                    }
                    else
                    {
                        gridVisible = true;
                        UIToolOptionPanel.instance.grid.activeStateIndex = 1;
                    }
                }
                else if (OptionsKeymapping.viewUnderground.IsPressed(e))
                {
                    if (tunnelVisible)
                    {
                        tunnelVisible = false;
                        UIToolOptionPanel.instance.underground.activeStateIndex = 0;
                    }
                    else
                    {
                        tunnelVisible = true;
                        UIToolOptionPanel.instance.underground.activeStateIndex = 1;
                    }
                }
                else if (OptionsKeymapping.activatePO.IsPressed(e))
                {
                    if (!HidePO)
                    {
                        if (PO.Active == false)
                        {
                            PO.Active = true;
                            UIToolOptionPanel.instance.PO_button.activeStateIndex = 1;
                            PO.ToolEnabled();
                        }
                        else
                        {
                            PO.Active = false;
                            UIToolOptionPanel.instance.PO_button.activeStateIndex = 0;
                        }
                        UIFilters.POToggled();
                    }
                }
                else if (OptionsKeymapping.convertToPO.IsPressed(e))
                {
                    if (!HidePO && PO.Enabled && ToolState == ToolStates.Default)
                    {
                        if (PO.Active == false)
                        {
                            PO.Active = true;
                            UIToolOptionPanel.instance.PO_button.activeStateIndex = 1;
                            PO.ToolEnabled();
                            UIFilters.POToggled();
                        }

                        ConvertToPOAction ca = new ConvertToPOAction();
                        ActionQueue.instance.Push(ca);
                        ActionQueue.instance.Do();
                    }
                }
                else if (OptionsKeymapping.alignHeights.IsPressed(e))
                {
                    ProcessAligning(AlignModes.Height);
                }
                else if (OptionsKeymapping.alignSlope.IsPressed(e))
                {
                    ProcessAligning(AlignModes.Slope);
                }
                else if (OptionsKeymapping.alignSlopeQuick.IsPressed(e))
                {
                    AlignMode = AlignModes.SlopeNode;

                    if (ToolState == ToolStates.Cloning || ToolState == ToolStates.RightDraggingClone)
                    {
                        StopCloning();
                    }

                    AlignSlopeAction asa = new AlignSlopeAction();
                    asa.followTerrain = followTerrain;
                    asa.IsQuick       = true;
                    ActionQueue.instance.Push(asa);
                    ActionQueue.instance.Do();
                    if (autoCloseAlignTools)
                    {
                        UIAlignTools.AlignToolsPanel.isVisible = false;
                    }
                    DeactivateAlignTool();
                }
                else if (OptionsKeymapping.alignInplace.IsPressed(e))
                {
                    ProcessAligning(AlignModes.Inplace);
                }
                else if (OptionsKeymapping.alignGroup.IsPressed(e))
                {
                    ProcessAligning(AlignModes.Group);
                }
                else if (OptionsKeymapping.alignRandom.IsPressed(e))
                {
                    AlignMode = AlignModes.Random;

                    if (ToolState == ToolStates.Cloning || ToolState == ToolStates.RightDraggingClone)
                    {
                        StopCloning();
                    }

                    AlignRandomAction action = new AlignRandomAction();
                    action.followTerrain = followTerrain;
                    ActionQueue.instance.Push(action);
                    ActionQueue.instance.Do();
                    DeactivateAlignTool();
                }

                if (ToolState == ToolStates.Cloning)
                {
                    if (ProcessMoveKeys(e, out Vector3 direction, out float angle))
                    {
                        CloneAction action = ActionQueue.instance.current as CloneAction;

                        action.moveDelta.y += direction.y * YFACTOR;
                        action.angleDelta  += angle;
                    }
                }
                else if (ToolState == ToolStates.Default && Action.selection.Count > 0)
                {
                    if (ProcessMoveKeys(e, out Vector3 direction, out float angle))
                    {
                        if (!(ActionQueue.instance.current is TransformAction action))
                        {
                            action = new TransformAction();
                            ActionQueue.instance.Push(action);
                        }

                        if (direction != Vector3.zero)
                        {
                            direction.x = direction.x * XFACTOR;
                            direction.y = direction.y * YFACTOR;
                            direction.z = direction.z * ZFACTOR;

                            if (!useCardinalMoves)
                            {
                                Matrix4x4 matrix4x = default(Matrix4x4);
                                matrix4x.SetTRS(Vector3.zero, Quaternion.AngleAxis(Camera.main.transform.localEulerAngles.y, Vector3.up), Vector3.one);

                                direction = matrix4x.MultiplyVector(direction);
                            }
                        }

                        action.moveDelta    += direction;
                        action.angleDelta   += angle;
                        action.followTerrain = followTerrain;

                        m_nextAction = ToolAction.Do;
                    }
                }
            }
        }
Beispiel #8
0
        /**
         *  After Save
         *	@param newRecord new
         *	@param success success
         *	@return success
         */
        protected override bool AfterSave(bool newRecord, bool success)
        {
            PO            project    = null;
            int           _client_ID = 0;
            StringBuilder _sql       = new StringBuilder();

            //_sql.Append("Select count(*) from  ad_table where tablename like 'FRPT_Project_Acct'");
            //_sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_Project_Acct')  AND OWNER LIKE '" + DB.GetSchema() + "'");
            _sql.Append(DBFunctionCollection.CheckTableExistence(DB.GetSchema(), "FRPT_Project_Acct"));
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                _sql.Clear();
                _sql.Append("Select L.Value From Ad_Ref_List L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where r.name='FRPT_RelatedTo' and l.name='Project'");
                var relatedtoProject = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));
                _client_ID = GetAD_Client_ID();
                _sql.Clear();
                _sql.Append("select C_AcctSchema_ID from C_AcctSchema where AD_CLIENT_ID=" + _client_ID);
                DataSet ds3 = new DataSet();
                ds3 = DB.ExecuteDataset(_sql.ToString(), null);
                if (ds3 != null && ds3.Tables[0].Rows.Count > 0)
                {
                    for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                    {
                        int _AcctSchema_ID = Util.GetValueOfInt(ds3.Tables[0].Rows[k]["C_AcctSchema_ID"]);
                        _sql.Clear();
                        _sql.Append("Select Frpt_Acctdefault_Id,C_Validcombination_Id,Frpt_Relatedto From Frpt_Acctschema_Default Where ISACTIVE='Y' AND AD_CLIENT_ID=" + _client_ID + "AND C_Acctschema_Id=" + _AcctSchema_ID);
                        DataSet ds = DB.ExecuteDataset(_sql.ToString(), null);
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                string _relatedTo = ds.Tables[0].Rows[i]["Frpt_Relatedto"].ToString();
                                if (_relatedTo != "" && (_relatedTo == relatedtoProject))
                                {
                                    _sql.Clear();
                                    _sql.Append("Select COUNT(*) From C_Project Bp Left Join FRPT_Project_Acct ca On Bp.C_Project_ID=ca.C_Project_ID And ca.Frpt_Acctdefault_Id=" + ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"] + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + _client_ID + " AND ca.C_Validcombination_Id = " + Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]) + " AND Bp.C_Project_ID = " + GetC_Project_ID());
                                    int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                    if (recordFound == 0)
                                    {
                                        project = MTable.GetPO(GetCtx(), "FRPT_Project_Acct", 0, null);
                                        project.Set_ValueNoCheck("AD_Org_ID", 0);
                                        project.Set_ValueNoCheck("C_Project_ID", Util.GetValueOfInt(GetC_Project_ID()));
                                        project.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                                        project.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]));
                                        project.Set_ValueNoCheck("C_AcctSchema_ID", _AcctSchema_ID);
                                        if (!project.Save())
                                        {
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (newRecord & success && (String.IsNullOrEmpty(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) || Util.GetValueOfString(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) == "Y"))
            {
                bool sucs = Insert_Accounting("C_Project_Acct", "C_AcctSchema_Default", null);
                //Karan. work done to show message if data not saved in accounting tab. but will save data in current tab.
                // Before this, data was being saved but giving message "record not saved".
                if (!sucs)
                {
                    log.SaveWarning("AcctNotSaved", "");
                }
            }

            //	Value/Name change
            MProject prjph = null;

            if (success && !newRecord &&
                (Is_ValueChanged("Value") || Is_ValueChanged("Name")))
            {
                MAccount.UpdateValueDescription(GetCtx(), "C_Project_ID=" + GetC_Project_ID(), Get_TrxName());
            }
            if (GetC_Campaign_ID() != 0)
            {
                MCampaign cam    = new MCampaign(GetCtx(), GetC_Campaign_ID(), null);
                decimal   plnAmt = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT COALESCE(SUM(pl.PlannedAmt),0)  FROM C_Project pl WHERE pl.IsActive = 'Y' AND pl.C_Campaign_ID = " + GetC_Campaign_ID()));
                cam.SetCosts(plnAmt);
                cam.Save();
            }
            else
            {
                prjph = new MProject(GetCtx(), GetC_Project_ID(), Get_Trx());
                if (!prjph.IsOpportunity())
                {
                    decimal plnAmt = Util.GetValueOfDecimal(DB.ExecuteScalar("SELECT COALESCE(SUM(PlannedAmt),0) FROM C_ProjectPhase WHERE IsActive= 'Y' AND C_Project_ID= " + GetC_Project_ID()));
                    DB.ExecuteQuery("UPDATE C_Project SET PlannedAmt=" + plnAmt + " WHERE C_Project_ID=" + GetC_Project_ID(), null, Get_Trx());
                }
            }
            return(success);
        }
Beispiel #9
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            /*Check PO in DB*/
            int ret = 0;
            /*Save The Edited Contract Info */
            PO newPO = new PO();

            newPO.IDContract          = txbIDContract.Text;
            newPO.IDPO                = txbPOCode.Text;
            newPO.PONumber            = txbPOName.Text;
            newPO.NumberOfDevice      = float.Parse(txbNumberDevice.Text);
            newPO.DateCreatedPO       = TimePickerDateCreatedPO.Value.ToString("yyyy-MM-dd");
            newPO.DurationConfirmPO   = TimePickerDateConfirmPO.Value.ToString("yyyy-MM-dd");
            newPO.DefaultActiveDatePO = TimepickerDefaultActive.Value.ToString("yyyy-MM-dd");
            newPO.DeadLinePO          = TimePickerDeadLinePO.Value.ToString("yyyy-MM-dd");
            newPO.TotalValuePO        = float.Parse(txbValuePO.Text);

            /*Create Folder Contract on F Disk*/
            string strContractDirectory = txbIDContract.Text.Replace('/', '_');

            strContractDirectory = strContractDirectory.Replace('-', '_');
            string strPODirectory = "F:\\OPM\\" + strContractDirectory + "\\" + txbPOName.Text;

            ret = newPO.GetDetailPO(txbPOCode.Text);
            if (0 == ret)
            {
                if (!Directory.Exists(strPODirectory))
                {
                    Directory.CreateDirectory(strPODirectory);
                    MessageBox.Show("Folder have been created!!!");
                }

                else
                {
                    MessageBox.Show("Folder already exist!!!");
                }
                ret = newPO.InsertNewPO(newPO);
                if (0 == ret)
                {
                    MessageBox.Show(ConstantVar.CreateNewPOFail);
                }
                else
                {
                    MessageBox.Show(ConstantVar.CreateNewPOSuccess);
                    UpdateCatalogPanel(txbPOName.Text);
                    /*Create Bao Lanh Thuc Hien Hop Dong*/
                    string fileBLTUPO_temp = @"F:\LP\BLPO_Template.docx";
                    string strBLTUPOName   = strPODirectory + "\\De nghi Bao lanh thuc hien & tam ung PO MSTT.docx";
                    /*truy Suất thông tin của Contract*/
                    ContractObj contractObj = new ContractObj();
                    ContractObj.GetObjectContract(txbIDContract.Text, ref contractObj);
                    this.Cursor = Cursors.WaitCursor;
                    OpmWordHandler.Create_BLTU_PO(fileBLTUPO_temp, strBLTUPOName, txbPOName.Text, txbIDContract.Text, contractObj.NameContract, contractObj.DateSigned, TimePickerDateCreatedPO.Value.ToString("yyyy-MM-dd"), txbValuePO.Text, txbTUPO.Text, contractObj.SiteB, txbActiveAfter.Text);
                    /*Send Email To DF*/

                    OPMEmailHandler.fSendEmail("Mail From DoanTD Gmail", strBLTUPOName);
                    this.Cursor = Cursors.Default;
                }

                /*Create Bao Lanh Thuc Hien Hop Dong*/
                //string filename = @"F:\LP\MSTT_Template.docx";
                //string strBLHPName = strContractDirectory + "\\Bao_Lanh_Hop_Dong.docx";

                //OpmWordHandler.CreateBLTH_Contract(filename, strBLHPName, tbContract.Text, tbBidName.Text, tbxDateSigned.Text, tbxSiteB.Text, txbGaranteeValue.Text, txbGaranteeActiveDate.Text);

                /*Send Email To DF*/
                //OPMEmailHandler.fSendEmail("Mail From DoanTD Gmail", strBLHPName);

                //UpdateCatalogPanel(txbPOCode.Text);
            }
        }
Beispiel #10
0
 public SearchResult(PO.Entry entry, SearchPlace place, int? index, int? start, int? length)
     : this(entry, new SearchPlace[] { place } , new int?[] { index } , new int?[] { start } , new int?[] { length })
 {
 }
Beispiel #11
0
 public SearchResult(PO.Entry entry, SearchPlace place)
     : this(entry, place, null, null, null)
 {
 }
Beispiel #12
0
        // GET: POes/Edit/5
        public ActionResult Edit(string id, bool update)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            //byte[] BytesArr = id.Split('-').Select(byte.Parse).ToArray();
            //id = new string( Encoding.UTF8.GetString(BytesArr).ToCharArray());
            //id = Encryption.Decrypt(id,"BZNS");

            decimal maxId = db.Suppliers.DefaultIfEmpty().Max(p => p == null ? 0 : p.Id);

            maxId += 1;
            ViewBag.SuggestedNewSuppId = maxId;

            List <MySaleType> myOptionLst = new List <MySaleType> {
                new MySaleType {
                    Text  = "Order",
                    Value = "false"
                },
                new MySaleType {
                    Text  = "Return",
                    Value = "true"
                }
            };

            ViewBag.OptionLst = myOptionLst;

            ////////////////
            List <MyPaymentMethod> myPaymentOptionLst = new List <MyPaymentMethod> {
                new MyPaymentMethod {
                    Text  = "Cash",
                    Value = "Cash"
                },
                new MyPaymentMethod {
                    Text  = "Online",
                    Value = "Online"
                },
                new MyPaymentMethod {
                    Text  = "Cheque",
                    Value = "Cheque"
                },
                new MyPaymentMethod {
                    Text  = "Other",
                    Value = "Other"
                }
            };

            ViewBag.PaymentMethodOptionLst = myPaymentOptionLst;

            List <MyUnitType> myUnitTypeOptionList = new List <MyUnitType> {
                new MyUnitType {
                    Text  = "Piece",
                    Value = "false"
                },
                new MyUnitType {
                    Text  = "Pack",
                    Value = "true"
                }
            };

            ViewBag.UnitTypeOptionList = myUnitTypeOptionList;
            string  iid  = Decode(id);
            Payment pmnt = db.Payments.Where(x => x.SOId == iid).FirstOrDefault();

            if (pmnt != null)
            {
                ViewBag.paymentMethod  = pmnt.PaymentMethod;
                ViewBag.paymentRemarks = pmnt.Remarks;
            }
            ///////////////////

            id = Decode(id);

            PO pO = db.POes.Find(id);

            if (pO == null)
            {
                return(HttpNotFound());
            }
            PurchaseOrderViewModel purchaseOrderViewModel = new PurchaseOrderViewModel();
            List <POD>             pod = db.PODs.Where(x => x.POId == id).ToList();

            purchaseOrderViewModel.Products            = _dbFilteredProducts;
            purchaseOrderViewModel.Suppliers           = _dbFilteredSuppliers;
            purchaseOrderViewModel.PurchaseOrderDetail = pod;
            pO.Id = Encryption.Encrypt(pO.Id);
            purchaseOrderViewModel.PurchaseOrder = pO;
            int orderQty       = 0;
            int orderQtyPiece  = 0; //orderQtyPiece 'P for piece'
            int returnQty      = 0;
            int returnQtyPiece = 0; //orderQtyPiece 'P for piece'

            foreach (var item in pod)
            {
                if (pO.PurchaseReturn == false)
                {
                    if (item.IsPack == true)
                    {//Pack
                        orderQty += (int)item.Quantity;
                    }
                    else
                    {//Item
                        orderQtyPiece += (int)item.Quantity;
                    }
                }
                else
                {
                    if (item.IsPack == true)
                    {//Pack
                        returnQty += (int)item.Quantity;
                    }
                    else
                    {//Item
                        returnQtyPiece += (int)item.Quantity;
                    }
                }
            }
            ViewBag.orderQty       = orderQty;
            ViewBag.orderQtyPiece  = orderQtyPiece;
            ViewBag.returnQty      = returnQty;
            ViewBag.returnQtyPiece = returnQtyPiece;
            //ViewBag.SupplierId = new SelectList(db.Suppliers, "Id", "Name", sO.SupplierId);
            ViewBag.SupplierName    = pO.Supplier.Name;
            ViewBag.SupplierAddress = pO.Supplier.Address;
            decimal subTotal = (decimal)(pO.PurchaseOrderAmount - pO.PurchaseReturnAmount - pO.Discount);

            ViewBag.SubTotal = subTotal;
            ViewBag.Total    = subTotal + (decimal)pO.PrevBalance;
            ViewBag.IsUpdate = update;
            ViewBag.IsReturn = pO.PurchaseReturn.ToString().ToLower();
            return(View(purchaseOrderViewModel));
        }
Beispiel #13
0
        //public ActionResult Edit([Bind(Prefix = "PurchaseOrder", Include = "BillAmount,Balance,BillPaid,Discount")] PO pO, [Bind(Prefix = "PurchaseOrderDetail", Include = "ProductId,Quantity")] List<POD> pOD)
        public ActionResult Edit(PurchaseOrderViewModel purchaseOrderViewModel1)
        {
            PO         newPO   = purchaseOrderViewModel1.PurchaseOrder;
            List <POD> newPODs = purchaseOrderViewModel1.PurchaseOrderDetail;

            if (ModelState.IsValid)
            {
                newPO.Id = Encryption.Decrypt(purchaseOrderViewModel1.PurchaseOrder.Id);                                                   //
                PO PO = db.POes.Where(x => x.Id == newPO.Id).FirstOrDefault();
                PO.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time")); //
                //PO.PurchaseReturn = false;//
                PO.BillAmount    = newPO.BillAmount;                                                                                       //
                PO.Discount      = newPO.Discount;                                                                                         //
                PO.BillPaid      = newPO.BillPaid;                                                                                         //
                PO.Balance       = newPO.Balance;                                                                                          //
                PO.Remarks       = newPO.Remarks;                                                                                          //
                PO.Remarks2      = newPO.Remarks;                                                                                          //
                PO.PaymentMethod = newPO.PaymentMethod;
                PO.PaymentDetail = newPO.PaymentDetail;

                //PO.POSerial = newPO.POSerial;//should be unchanged

                ///////////////////////////////////////////

                //Supplier cust = db.Suppliers.FirstOrDefault(x => x.Id == newPO.SupplierId);
                Supplier supplier = db.Suppliers.Where(x => x.Id == newPO.SupplierId).FirstOrDefault();
                if (supplier == null)
                {//its means new supplier(not in db)
                 //PO.SupplierId = 10;
                 //int maxId = db.Suppliers.Max(p => p.Id);
                    supplier = purchaseOrderViewModel1.Supplier;
                    decimal maxId = db.Suppliers.DefaultIfEmpty().Max(p => p == null ? 0 : p.Id);
                    maxId += 1;

                    supplier.Id = maxId;
                    //supplier.Balance = newPO.Balance;
                    db.Suppliers.Add(supplier);
                }
                else
                {
                    db.Entry(supplier).State = EntityState.Modified;
                }

                if (PO.SupplierId != newPO.SupplierId)
                {//POme other db supplier
                 //first revert the previous supplier balance
                    Supplier oldSupplier = db.Suppliers.Where(x => x.Id == PO.SupplierId).FirstOrDefault();
                    oldSupplier.Balance         = _dbFilteredPO.Where(x => x.Id == PO.Id).FirstOrDefault().PrevBalance;
                    db.Entry(oldSupplier).State = EntityState.Modified;
                }

                PO.PrevBalance = newPO.PrevBalance;//
                // assign balance of this supplier
                //Supplier supplier = db.Suppliers.Where(x => x.Id == newPO.SupplierId).FirstOrDefault();
                supplier.Balance = newPO.Balance;
                //assign supplier and supplierId in PO
                PO.SupplierId = newPO.SupplierId;
                PO.Supplier   = supplier;

                /////////////////////////////////////////////////////////////////////////////



                List <POD> oldPODs = db.PODs.Where(x => x.POId == newPO.Id).ToList();

                //handling old prodcts quantity. add old quantites back to the stock, then in next loop product quantity will be minus. this is simple and stateforward.
                foreach (POD pod in oldPODs)
                {
                    Product product = db.Products.FirstOrDefault(x => x.Id == pod.ProductId);
                    if (pod.SaleType == false)//purchase
                    {
                        //product.Stock -= pod.Quantity;

                        if (pod.IsPack == false)
                        {
                            decimal qty = (decimal)pod.Quantity;// / (decimal)product.PerPack;
                            product.Stock -= qty;
                        }
                        else
                        {
                            product.Stock -= (int)pod.Quantity * pod.PerPack;
                        }
                    }
                    else//return
                    {
                        //product.Stock += pod.Quantity;

                        if (pod.IsPack == false)
                        {
                            decimal qty = (decimal)pod.Quantity;// / (decimal)product.PerPack;
                            product.Stock += qty;
                        }
                        else
                        {
                            product.Stock += (int)pod.Quantity * pod.PerPack;
                        }
                    }
                    db.Entry(product).State = EntityState.Modified;
                }

                db.PODs.RemoveRange(oldPODs);
                //////////////////////////////////////////////////////////////////////////////

                PO.PurchaseOrderAmount  = 0;
                PO.PurchaseReturnAmount = 0;
                PO.PurchaseOrderQty     = 0;
                PO.PurchaseReturnQty    = 0;
                //PO.Profit = 0;
                int sno = 0;

                if (newPODs != null)
                {
                    foreach (POD pod in newPODs)
                    {
                        sno      += 1;
                        pod.PODId = sno;
                        pod.PO    = PO;
                        pod.POId  = PO.Id;

                        Product product = db.Products.FirstOrDefault(x => x.Id == pod.ProductId);
                        //POd.purchasePrice is now from view
                        //POd.PurchasePrice = product.PurchasePrice;
                        //dont do this. calculation are geting wrong. when user open an old bill and just press save. all calculations distrubs
                        //pod.PurchasePrice = product.PurchasePrice;
                        if (pod.Quantity == null)
                        {
                            pod.Quantity = 0;
                        }
                        pod.OpeningStock = product.Stock;
                        if (pod.SaleType == true)//return
                        {
                            if (pod.IsPack == false)
                            {
                                PO.PurchaseReturnAmount += (decimal)(pod.Quantity * pod.PurchasePrice);
                                decimal qty = (decimal)pod.Quantity; // / (decimal)product.PerPack;
                                product.Stock        -= qty;
                                PO.PurchaseReturnQty += qty;         //(int)sod.Quantity;
                            }
                            else
                            {
                                PO.PurchaseReturnAmount += (decimal)(pod.Quantity * pod.PurchasePrice * pod.PerPack);
                                product.Stock           -= (int)pod.Quantity * pod.PerPack;

                                PO.PurchaseReturnQty += (int)pod.Quantity * pod.PerPack;
                            }
                        }
                        else//purchase
                        {
                            if (pod.IsPack == false)
                            {//piece
                                PO.PurchaseOrderAmount += (decimal)(pod.Quantity * pod.PurchasePrice);
                                //int pieceSold = (int)(sod.Quantity * product.Stock);
                                decimal qty = (decimal)pod.Quantity;// / (decimal)product.PerPack;
                                product.Stock += qty;

                                PO.PurchaseOrderQty += qty;//(int)sod.Quantity;
                            }
                            else
                            {//pack
                                PO.PurchaseOrderAmount += (decimal)(pod.Quantity * pod.PurchasePrice * pod.PerPack);
                                product.Stock          += (int)pod.Quantity * pod.PerPack;

                                PO.PurchaseOrderQty += (int)pod.Quantity * pod.PerPack;
                            }
                        }
                    }
                    //PO.Profit -= (decimal)PO.Discount;
                    db.Entry(PO).State = EntityState.Modified;
                    db.Entry(PO).Property(x => x.POSerial).IsModified = false;
                    db.PODs.AddRange(newPODs);
                }
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }

            //ViewBag.SupplierId = new SelectList(db.Suppliers, "Id", "Name", PO.SupplierId);
            //return View(PO);
            PurchaseOrderViewModel purchaseOrderViewModel = new PurchaseOrderViewModel();

            purchaseOrderViewModel.Products = db.Products;
            return(View(purchaseOrderViewModel));
            //return View();
        }
Beispiel #14
0
        public ActionResult Create([Bind(Prefix = "Supplier", Include = "Name,Address")] Supplier Supplier, [Bind(Prefix = "PurchaseOrder", Include = "BillAmount,Balance,PrevBalance,BillPaid,Discount,SupplierId,Remarks,Remarks2,PaymentMethod,PaymentDetail,PurchaseReturn,AccountId")] PO pO, [Bind(Prefix = "PurchaseOrderDetail", Include = "ProductId,Quantity,SaleType,PerPack,IsPack,PurchasePrice")] List <POD> pOD)

        {
            //PO pO = new PO();
            if (ModelState.IsValid)
            {
                Supplier supp = db.Suppliers.FirstOrDefault(x => x.Id == pO.SupplierId);
                if (supp == null)
                {//its means new customer
                    //pO.SupplierId = 10;
                    //int maxId = db.Suppliers.Max(p => p.Id);
                    decimal maxId = db.Suppliers.DefaultIfEmpty().Max(p => p == null ? 0 : p.Id);
                    maxId += 1;
                    Business CurrentBusiness = (Business)Session["CurrentBusiness"];
                    Supplier.Id    = maxId;
                    Supplier.bizId = CurrentBusiness.Id;

                    Supplier.Balance = pO.Balance;
                    db.Suppliers.Add(Supplier);
                    //db.SaveChanges();
                }
                else
                {//its means old customer. old customer balance should be updated.
                    //Supplier.Id = (int)pO.SupplierId;
                    supp.Balance         = pO.Balance;
                    db.Entry(supp).State = EntityState.Modified;
                    //db.SaveChanges();

                    //Payment payment = new Payment();
                    //payment = db.Payments.Find(orderId);
                    //payment.Status = true;
                    //db.Entry(payment).State = EntityState.Modified;
                    //db.SaveChanges();
                }

                ////////////////////////////////////////
                //int maxId = db.POes.Max(p => p.Auto);
                int maxId1 = (int)db.POes.DefaultIfEmpty().Max(p => p == null ? 0 : p.POSerial);
                maxId1     += 1;
                pO.POSerial = maxId1;
                //pO.Date = DateTime.Now;
                pO.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time"));
                //pO.SaleReturn = false;
                pO.Id = System.Guid.NewGuid().ToString().ToUpper();
                pO.PurchaseOrderAmount  = 0;
                pO.PurchaseReturnAmount = 0;
                pO.PurchaseOrderQty     = 0;
                pO.PurchaseReturnQty    = 0;
                Employee emp = (Employee)Session["CurrentUser"];
                pO.EmployeeId = emp.Id;
                db.POes.Add(pO);
                //db.SaveChanges();
                int sno = 0;
                if (pOD != null)
                {
                    //pOD.RemoveAll(so => so.ProductId == null);
                    foreach (POD pod in pOD)
                    {
                        sno      += 1;
                        pod.PODId = sno;
                        pod.PO    = pO;
                        pod.POId  = pO.Id;

                        Product product = db.Products.FirstOrDefault(x => x.Id == pod.ProductId);

                        //dont do this. when user enter manual purchase price that will not happen. it does not reflect in bill and calculations geting wrong
                        //pod.PurchasePrice = product.PurchasePrice;
                        if (pod.Quantity == null)
                        {
                            pod.Quantity = 0;
                        }
                        pod.OpeningStock = product.Stock;
                        if (pod.SaleType == true)//return
                        {
                            if (pod.IsPack == false)
                            {
                                pO.PurchaseReturnAmount += (decimal)(pod.Quantity * pod.PurchasePrice);
                                decimal qty = (decimal)pod.Quantity; // / (decimal)product.PerPack;
                                product.Stock        -= qty;
                                pO.PurchaseReturnQty += qty;         //(int)sod.Quantity;
                            }
                            else
                            {
                                pO.PurchaseReturnAmount += (decimal)(pod.Quantity * pod.PurchasePrice * pod.PerPack);
                                product.Stock           -= (int)pod.Quantity * pod.PerPack;

                                pO.PurchaseReturnQty += (int)pod.Quantity * pod.PerPack;
                            }
                        }
                        else//purchase
                        {
                            if (pod.IsPack == false)
                            {//piece
                                pO.PurchaseOrderAmount += (decimal)(pod.Quantity * pod.PurchasePrice);
                                //int pieceSold = (int)(sod.Quantity * product.Stock);
                                decimal qty = (decimal)pod.Quantity;// / (decimal)product.PerPack;
                                product.Stock += qty;

                                pO.PurchaseOrderQty += qty;//(int)sod.Quantity;
                            }
                            else
                            {//pack
                                pO.PurchaseOrderAmount += (decimal)(pod.Quantity * pod.PurchasePrice * pod.PerPack);
                                product.Stock          += (int)pod.Quantity * pod.PerPack;

                                pO.PurchaseOrderQty += (int)pod.Quantity * pod.PerPack;
                            }
                        }
                    }
                    db.PODs.AddRange(pOD);
                }
                string POId;
                ////////////////////////////v deffer the duplicate error
                int previousbillNum = maxId1 - 1;
                PO  previousBill    = db.POes.Where(x => x.POSerial == previousbillNum).FirstOrDefault();

                if (previousBill != null)
                {
                    DateTime PrvTime  = (DateTime)previousBill.Date; //previous bill time
                    DateTime thisTime = (DateTime)pO.Date;           //this bill time
                    TimeSpan span     = thisTime.Subtract(PrvTime);

                    if (previousBill.BillAmount == pO.BillAmount && previousBill.BillPaid == pO.BillPaid &&
                        previousBill.SupplierId == pO.SupplierId && previousBill.Discount == pO.Discount &&
                        previousBill.PurchaseOrderAmount == pO.PurchaseOrderAmount && previousBill.PurchaseOrderQty == pO.PurchaseOrderQty &&
                        previousBill.PurchaseReturnAmount == pO.PurchaseReturnAmount && previousBill.PurchaseReturnQty == pO.PurchaseReturnQty)
                    //&& span.TotalSeconds < 60)
                    {
                        //Duplicate bill found. don't do anything
                        POId = string.Join("-", ASCIIEncoding.ASCII.GetBytes(Encryption.Encrypt(previousBill.Id)));

                        string path = Server.MapPath("~/log.txt");
                        System.IO.File.AppendAllText(path, DateTime.Now.ToString("dd/MM/yy hh:mm tt") + "\tPO" + System.Environment.NewLine);
                    }
                    else
                    {
                        db.SaveChanges();
                        POId = string.Join("-", ASCIIEncoding.ASCII.GetBytes(Encryption.Encrypt(pO.Id)));
                    }
                }
                else
                {
                    db.SaveChanges();
                    POId = string.Join("-", ASCIIEncoding.ASCII.GetBytes(Encryption.Encrypt(pO.Id)));
                }

                ViewBag.POIDEnc = POId;


                ////////////////////////////^ deffer the duplicate error


                //SqlParameter param1 = new SqlParameter("@PurchaseOrderID", pO.Id);
                ////var result = db.Database.ExecuteSqlCommand("spSOReceipt @PurchaseOrderID", param1);
                //var result = db.Database.SqlQuery<Object>("spSOReceipt @PurchaseOrderID", param1);


                //var cr = new ReportDocument();
                //cr.Load(@"E:\PROJECTS\MYBUSINESS - v.4.6\MYBUSINESS\Reports\SOReceipt.rpt");
                //cr.DataDefinition.RecordSelectionFormula = "{PurchaseOrderID} = '" + pO.Id + "'";
                //cr.PrintToPrinter(1, true, 0, 0);


                ////////////////////////finalized
                //string pathh = HttpRuntime.AppDomainAppPath;
                //ReportDocument reportDocument = new ReportDocument();
                //reportDocument.Load(pathh + @"Reports\SOReceipt.rpt");
                //reportDocument.SetParameterValue("@PurchaseOrderID", pO.Id);
                //System.Drawing.Printing.PrinterSettings printerSettings = new System.Drawing.Printing.PrinterSettings();
                ////printerSettings.PrinterName = PrinterName;
                //reportDocument.PrintToPrinter(printerSettings, new PageSettings(), false);
                /////////////////////////////////////


                //string POId = string.Join("-", ASCIIEncoding.ASCII.GetBytes(Encryption.Encrypt(pO.Id)));
                //return PrintSO(POId);
                return(PrintSO3(POId));

                //return RedirectToAction("Index");
            }

            //ViewBag.SupplierId = new SelectList(_dbFilteredSuppliers, "Id", "Name", pO.SupplierId);
            //return View(pO);
            PurchaseOrderViewModel purchaseOrderViewModel = new PurchaseOrderViewModel();

            purchaseOrderViewModel.Suppliers = _dbFilteredSuppliers;
            purchaseOrderViewModel.Products  = _dbFilteredProducts;

            return(View(purchaseOrderViewModel));
            //return View();
        }
        /// <SUMmary>
        ///  Sales Order Products
        /// </SUMmary>
        /// <returns>No of lines created</returns>
        private int SalesOrderProducts()
        {
            sql = "SELECT ol.m_product_id,ol.QtyOrdered,M_AttributeSetInstance_ID,ol.C_UOM_ID," +
                  " ol.C_OrderLine_ID,o.C_Order_ID,(NVL(PriceEntered,0) * NVL(QtyEntered,0)) AS Price,o.C_Currency_ID FROM C_Order o " +
                  " INNER JOIN C_OrderLine ol ON o.C_Order_ID = ol.C_Order_ID " +
                  " INNER JOIN C_Doctype d ON o.c_DocTypeTarget_ID = d.C_Doctype_ID   " +
                  " WHERE d.DocBaseType='" + MDocBaseType.DOCBASETYPE_SALESORDER + "' " +
                  " AND d.DocSubTypeSo NOT IN ('" + MDocType.DOCSUBTYPESO_BlanketOrder + "','" + MDocType.DOCSUBTYPESO_Proposal + "')" +
                  " AND o.IsSOTrx='Y' AND o.IsReturnTrx='N' AND o.AD_Org_ID = " + mf.GetAD_Org_ID() +
                  " AND o.DateOrdered BETWEEN (SELECT startdate FROM C_Period WHERE C_Period_ID = " + C_Period_ID + ")  " +
                  " AND (SELECT enddate FROM C_Period WHERE C_Period_ID = " + C_Period_ID + ") AND ol.QtyOrdered > ol.QtyDelivered " +
                  " AND ol.C_OrderLine_ID NOT IN (SELECT C_OrderLine_ID FROM va073_masterforecastlinedetail WHERE " +
                  "AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_Period_ID=" + C_Period_ID + ") AND NVL(ol.M_Product_ID,0)>0 AND o.DocStatus IN('CO','CL') ";

            sql = MRole.GetDefault(GetCtx()).AddAccessSQL(sql, "C_Order", true, true); // fully qualified - RO

            dsOrder = new DataSet();
            dsOrder = DB.ExecuteDataset(sql, null, mf.Get_Trx());
            if (dsOrder != null && dsOrder.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dsOrder.Tables[0].Rows.Count; i++)
                {
                    //create MasterForecastLine
                    mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_Product_ID"]),
                                                    Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]), 0, 0, 0);
                    if (!mfLine.Save())
                    {
                        ValueNamePair vp = VLogger.RetrieveError();
                        if (vp != null)
                        {
                            log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName());
                        }
                        else
                        {
                            log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved"));
                        }
                    }
                    else
                    {
                        LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0)+10  FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(), null, mf.Get_Trx()));
                        //Convert Line Amount as per Currency Defined ON  Master Forecast
                        ConvertedAmt = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOrder.Tables[0].Rows[i]["Price"]),
                                                               Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_Currency_ID"]), Currency,
                                                               Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")),
                                                               Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID());

                        //Create Product Line Details
                        po = GenerateProductLineDetails(mfLine, LineNo, Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_Order_ID"]),
                                                        Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_OrderLine_ID"]), 0, 0, 0, 0,
                                                        C_Period_ID, Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_Product_ID"]),
                                                        Util.GetValueOfDecimal(dsOrder.Tables[0].Rows[i]["QtyOrdered"]), ConvertedAmt,
                                                        Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]));
                        if (!po.Save())
                        {
                            ValueNamePair vp = VLogger.RetrieveError();
                            if (vp != null)
                            {
                                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + "for OrderLine" + Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_OrderLine_ID"])
                                        + vp.GetValue() + " - " + vp.GetName());
                            }
                            else
                            {
                                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + "for OrderLine" + Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_OrderLine_ID"]));
                            }
                        }
                        else
                        {
                            Count++;
                            LineNo += 10;
                            //Update quantities AND price at Product line
                            sql = "UPDATE c_masterforecastline SET " +
                                  "ForcastQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Forecast_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                  "OppQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Project_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                  "VA073_SalesOrderQty =(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Order_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                  "TotalQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE  c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + ") , " +
                                  "Price= (Round((SELECT NVL(SUM(price),0)/ NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                  StdPrecision + ")), " +
                                  "PlannedRevenue =(ROUND((SELECT SUM(price) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + ")," + StdPrecision + "))" +
                                  " WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID();

                            DB.ExecuteQuery(sql, null, mf.Get_Trx());
                        }
                    }
                }
            }
            else
            {
                log.Log(Level.INFO, Msg.GetMsg(GetCtx(), "NoRecordFoundSalesOrder"));
            }
            return(Count);
        }
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override bool BeforeSave(bool newRecord)
        {
            if (Is_ValueChanged("DueAmt"))
            {
                log.Fine("beforeSave");
                SetIsValid(false);
            }
            oldDueAmt = Util.GetValueOfDecimal(Get_ValueOld("DueAmt"));

            if (Env.IsModuleInstalled("VA009_"))
            {
                // get invoice currency for rounding
                MCurrency currency = MCurrency.Get(GetCtx(), GetC_Currency_ID());
                SetDueAmt(Decimal.Round(GetDueAmt(), currency.GetStdPrecision()));
                SetVA009_PaidAmntInvce(Decimal.Round(GetVA009_PaidAmntInvce(), currency.GetStdPrecision()));

                // when invoice schedule have payment reference then need to check payment mode on payment window & update here
                if (GetC_Payment_ID() > 0)
                {
                    #region for payment
                    MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx());
                    SetVA009_PaymentMethod_ID(payment.GetVA009_PaymentMethod_ID());

                    // get payment method detail -- update to here
                    DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod
                                          WHERE VA009_PaymentMethod_ID = " + payment.GetVA009_PaymentMethod_ID(), null, Get_Trx());
                    if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                    {
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                        {
                            SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                        }
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                        {
                            SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                        }
                        SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                    }
                    #endregion
                }
                else if (GetC_CashLine_ID() > 0)
                {
                    #region For Cash
                    // when invoice schedule have cashline reference then need to check
                    // payment mode of "Cash" type having currency is null on "Payment Method" window & update here
                    DataSet dsPaymentMethod = (DB.ExecuteDataset(@"SELECT VA009_PaymentMethod_ID, VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger 
                                       FROM VA009_PaymentMethod WHERE IsActive = 'Y' 
                                       AND AD_Client_ID = " + GetAD_Client_ID() + @" AND VA009_PaymentBaseType = 'B' AND NVL(C_Currency_ID , 0) = 0", null, Get_Trx()));
                    if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                    {
                        SetVA009_PaymentMethod_ID(Util.GetValueOfInt(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMethod_ID"]));
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                        {
                            SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                        }
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                        {
                            SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                        }
                        SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                    }
                    else
                    {
                        #region when we not found record of "Cash" then we will create a new rcord on Payment Method for Cash
                        string sql     = @"SELECT AD_TABLE_ID  FROM AD_TABLE WHERE tablename LIKE 'VA009_PaymentMethod' AND IsActive = 'Y'";
                        int    tableId = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                        MTable tbl     = new MTable(GetCtx(), tableId, Get_Trx());
                        PO     po      = tbl.GetPO(GetCtx(), 0, Get_Trx());
                        po.SetAD_Client_ID(GetAD_Client_ID());
                        po.SetAD_Org_ID(0); // Recod will be created in (*) Organization
                        po.Set_Value("Value", "By Cash");
                        po.Set_Value("VA009_Name", "By Cash");
                        po.Set_Value("IsActive", true);
                        po.Set_Value("VA009_PaymentBaseType", "B");
                        po.Set_Value("VA009_PaymentRule", "M");
                        po.Set_Value("VA009_PaymentMode", "C");
                        po.Set_Value("VA009_PaymentType", "S");
                        po.Set_Value("VA009_PaymentTrigger", "S");
                        po.Set_Value("C_Currency_ID", null);
                        po.Set_Value("VA009_InitiatePay", false);
                        if (!po.Save(Get_Trx()))
                        {
                            ValueNamePair pp = VLogger.RetrieveError();
                            log.Info("Error Occured when try to save record on Payment Method for Cash. Error Type : " + pp.GetValue());
                        }
                        else
                        {
                            SetVA009_PaymentMethod_ID(Util.GetValueOfInt(po.Get_Value("VA009_PaymentMethod_ID")));
                            SetVA009_PaymentMode("C");
                            SetVA009_PaymentType("S");
                            SetVA009_PaymentTrigger("S");
                        }
                        #endregion
                    }
                    #endregion
                }
            }
            // to set processing false because in case of new schedule processing is set to be false
            if (newRecord)
            {
                SetProcessing(false);

                // when schedile is not paid and invoice hedaer having "Hold Payment", then set "Hold payment" on schedule also
                if (Get_ColumnIndex("IsHoldPayment") > 0 && (GetC_Payment_ID() == 0 && GetC_CashLine_ID() == 0))
                {
                    String sql           = "SELECT IsHoldPayment FROM C_Invoice WHERE C_Invoice_ID = " + GetC_Invoice_ID();
                    String IsHoldPayment = Util.GetValueOfString(DB.ExecuteScalar(sql, null, Get_Trx()));
                    SetIsHoldPayment(IsHoldPayment.Equals("Y"));
                }
            }
            return(true);
        }
Beispiel #17
0
 public SearchResult(PO.Entry entry, List<SearchPlace> places, List<int?> indexes, List<int?> starts, List<int?> lengths)
     : this(entry, places.ToArray(), indexes.ToArray(), starts.ToArray(), lengths.ToArray())
 {
 }
Beispiel #18
0
 internal static DataLine CreateNew(PO.Entry entry, DataLine.Kinds kind, int? index, bool isContinuation, IO.TextLine addRelativeTo, bool addRelativeToBefore, string text)
 {
     if (entry == null)
         throw new ArgumentNullException("entry");
     if (addRelativeTo == null)
         throw new ArgumentNullException("addRelativeTo");
     int insertAt = entry.File.TextFile.Lines.IndexOf(addRelativeTo);
     if (insertAt < 0)
         throw new ArgumentOutOfRangeException("addRelativeTo");
     if (!addRelativeToBefore)
         insertAt++;
     IO.TextLine textLine = new IO.TextLine(BuildTextFileData(kind, index, isContinuation, text));
     entry.File.TextFile.Lines.Insert(insertAt, textLine);
     DataLine result;
     if (index.HasValue)
         result = new IndexedDataLine(entry.File, textLine, isContinuation, kind, text, index.Value);
     else
         result = new DataLine(entry.File, textLine, isContinuation, kind, text);
     entry.LineAdded(result);
     return result;
 }
Beispiel #19
0
 public SearchResult(PO.Entry entry, SearchPlace[] places, int?[] indexes, int?[] starts, int?[] lengths)
     : this(entry)
 {
     this.Places.AddRange(places);
     this.Indexes.AddRange(indexes);
     this.Starts.AddRange(starts);
     this.Lengths.AddRange(lengths);
 }
Beispiel #20
0
        private bool isInputValid()
        {
            //sanitize inputs
            txtPONo.Text  = DBUtil.sanitize(txtPONo.Text);
            txtNotes.Text = DBUtil.sanitize(txtNotes.Text);

            if (string.IsNullOrEmpty(txtPONo.Text))
            {
                return(Tools.inputError <TextBox>(txtPONo, "PO Number is required"));
            }
            else if (PO.isPONoExist(txtPONo.Text))
            {
                return(Tools.inputError <TextBox>(txtPONo, "PO Number already exists"));
            }
            else if (iddl_Vendor.Enabled && iddl_Vendor.SelectedIndex == -1)
            {
                return(iddl_Vendor.SelectedValueError("Please select a vendor"));
            }
            else if (iddl_Customers.Enabled && iddl_Customers.SelectedIndex == -1)
            {
                return(iddl_Customers.SelectedValueError("Please select a customer"));
            }

            //validate items
            bool isValid = true;
            bool hasValidLine = false;
            bool validProductName, validQty;

            foreach (DataGridViewRow row in gridPOItems.Rows)
            {
                row.Cells[col_gridPOItems_productName.Name].ErrorText = "";
                row.Cells[col_gridPOItems_qty.Name].ErrorText         = "";

                validProductName = isValidProductName(row);
                validQty         = isValidQty(row);

                if (!hasValidLine && validProductName && validQty)
                {
                    hasValidLine = true;
                }

                if (!validProductName && !validQty)
                {
                    continue;
                }
                else
                {
                    if (!validProductName)
                    {
                        row.Cells[col_gridPOItems_productName.Name].ErrorText = "missing description";
                        isValid = false;
                    }
                    else if (!validQty)
                    {
                        row.Cells[col_gridPOItems_qty.Name].ErrorText = "invalid qty";
                        isValid = false;
                    }
                }
            }

            if (!isValid)
            {
                return(Tools.showError("Please fix errors to continue"));
            }
            else if (!hasValidLine)
            {
                return(Tools.showError("Please add a valid item to continue"));
            }

            return(true);
        }
Beispiel #21
0
 private SearchResult(PO.Entry entry)
 {
     this.Entry = entry;
     this.Places = new List<SearchPlace>();
     this.Indexes = new List<int?>();
     this.Starts = new List<int?>();
     this.Lengths = new List<int?>();
 }
 public static bool insertSupplierInvoice(APCEntities APCContext, string supplierOriNo, decimal paymentDue, DateTime dueDate, PO po)
 {
     if (supplierOriNo.Trim() != "")
     {
         SupplierInvoice supplierInvoice = new SupplierInvoice();
         supplierInvoice.SupplierOriNo = supplierOriNo;
         supplierInvoice.PaymentDue    = paymentDue;
         supplierInvoice.DueDate       = dueDate;
         supplierInvoice.PO            = po;
         supplierInvoice.Paid          = false;
         APCContext.AddToSupplierInvoice(supplierInvoice);
         APCContext.SaveChanges();
         return(true);
     }
     else
     {
         return(false);
     }
 }
Beispiel #23
0
 public SearchResultDescribed(PO.Entry entry, SearchPlace place, string description)
     : this(entry, place, null, null, null, description)
 {
 }
 internal static Chunk Create(PO.Chunk chunk)
 {
     return new Chunk().Set(chunk.ID, chunk.StartDateTimeOffset, chunk.StopDateTimeOffset, chunk.DurationTimeSpan);
 }
Beispiel #25
0
 public SearchResultDescribed(PO.Entry entry, SearchPlace place, int? index, int? start, int? length, string description)
     : this(entry, new SearchPlace[] { place } , new int?[] { index } , new int?[] { start } , new int?[] { length } , description)
 {
 }
Beispiel #26
0
 internal void RemoveLine(PO.Line line)
 {
     if (line == null)
         throw new ArgumentNullException("line");
     int myIndex = this._lines.IndexOf(line);
     if (myIndex < 0)
         throw new Exception("Line not found.");
     if (!this._file.TextFile.Lines.Remove(line.Source))
         throw new Exception("Text line not found.");
     this._lines.RemoveAt(myIndex);
 }
Beispiel #27
0
 public SearchResultDescribed(PO.Entry entry, List<SearchPlace> places, List<int?> indexes, List<int?> starts, List<int?> lengths, string description)
     : this(entry, places.ToArray(), indexes.ToArray(), starts.ToArray(), lengths.ToArray(), description)
 {
 }
Beispiel #28
0
 /// <summary>
 /// Create a new PO object.
 /// </summary>
 /// <param name="id">Initial value of Id.</param>
 public static PO CreatePO(int id)
 {
     PO pO = new PO();
     pO.Id = id;
     return pO;
 }
Beispiel #29
0
 public SearchResultDescribed(PO.Entry entry, SearchPlace[] places, int?[] indexes, int?[] starts, int?[] lengths, string description)
     : base(entry, places, indexes, starts, lengths)
 {
     this.Description = (description == null) ? "" : description;
 }
        /// <SUMmary>
        ///  Oppportunity Products
        /// </SUMmary>
        /// <returns>No of Lines created</returns>
        private int OnlyOpportunityProducts()
        {
            if (!Env.IsModuleInstalled("VA073_"))
            {
                //sql = " SELECT distinct(pl.m_product_id) FROM c_projectline pl INNER JOIN c_project p ON p.c_project_id = pl.c_project_id WHERE p.c_order_id IS NULL"
                //    + " AND p.ref_order_id IS  ANDNULL pl.m_product_id NOT IN (SELECT DISTINCT(M_Product_ID) FROM c_forecastline fl "
                //    + " INNER JOIN c_forecast f ON (fl.c_forecast_id = f.c_forecast_id) WHERE f.c_period_id = " + C_Period_ID
                //    + " AND f.ad_client_id = " + GetCtx().GetAD_Client_ID() + " AND fl.isactive = 'Y')";
                sql = " SELECT DISTINCT(pl.m_product_id),SUM(nvl(pl.plannedqty,0)) AS Quantity ,SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) AS Price, " +
                      "p.C_Currency_ID,pl.C_UOM_ID " +
                      "FROM c_projectline pl " +
                      "INNER JOIN c_project p ON p.c_project_id = pl.c_project_id " +
                      "WHERE p.c_order_id IS NULL"
                      //       + " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " +
                      + " AND p.ref_order_id IS NULL AND pl.m_product_id NOT IN (SELECT m_product_id FROM c_masterforecastline WHERE isactive = 'Y'" +
                      " AND c_masterforecast_id = " + GetRecord_ID() + ") AND p.AD_CLient_ID= " + mf.GetAD_Client_ID() +
                      " AND pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " +
                      " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " +
                      " GROUP BY C_Currency_ID,pl.C_UOM_ID,pl.m_product_id";

                //IDataReader idr = null;
                try
                {
                    Decimal?totalQtyOpp   = 0;
                    Decimal?totalPriceOpp = 0;
                    //sql = "SELECT SUM(nvl(pl.plannedqty,0)) AS Quantity ,SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) AS Price, p.C_Currency_ID,pl.C_UOM_ID" +
                    //    " FROM c_projectline pl INNER JOIN c_project p ON (p.c_project_id = pl.c_project_id) "
                    //      + " WHERE " +
                    //       "pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") "
                    //       + " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " +
                    //       "AND pl.m_product_id =  " + Util.GetValueOfInt(idr[0]) + " AND p.c_order_id IS NULL AND p.ref_order_id IS NULL AND pl.isactive = 'Y'"
                    //        + " GROUP BY C_Currency_ID,pl.C_UOM_ID";

                    // totalQtyOpp = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null));

                    //sql = " SELECT SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) FROM c_projectline pl INNER JOIN c_project p ON (p.c_project_id = pl.c_project_id) "
                    //    + " WHERE  " +
                    //"pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") "
                    //+ " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " +
                    //" AND pl.m_product_id =  " + Util.GetValueOfInt(idr[0]) + " AND p.c_order_id IS NULL AND p.ref_order_id IS NULL AND pl.isactive = 'Y'";
                    //totalPriceOpp = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null));

                    dsOpp = DB.ExecuteDataset(sql, null, mf.Get_Trx());
                    if (dsOpp != null && dsOpp.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < dsOpp.Tables[0].Rows.Count; i++)
                        {
                            //Conversion from Project to MasterForecast Currency
                            totalPriceOpp = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["Price"]),
                                                                    Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_Currency_ID"]), Currency,
                                                                    Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")),
                                                                    Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID());

                            //Conversion from BaseUOM to UOM on Project Line
                            totalQtyOpp = MUOMConversion.ConvertProductFrom(mf.GetCtx(), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]),
                                                                            Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["Quantity"]));

                            if (totalQtyOpp == null)
                            {
                                totalQtyOpp = Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["Quantity"]);
                            }

                            if (totalQtyOpp.Value > 0)
                            {
                                Decimal?avgPrice = Decimal.Divide(totalPriceOpp.Value, totalQtyOpp.Value);
                                avgPrice = Decimal.Round(avgPrice.Value, StdPrecision, MidpointRounding.AwayFromZero);

                                mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]), 0, Util.GetValueOfDecimal(Decimal.Zero), totalQtyOpp, avgPrice);
                                if (!mfLine.Save())
                                {
                                    ValueNamePair vp = VLogger.RetrieveError();
                                    if (vp != null)
                                    {
                                        log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName());
                                    }
                                    else
                                    {
                                        log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved"));
                                    }
                                }
                            }
                        }
                        //if (idr != null)
                        //{
                        //    idr.Close();
                        //    idr = null;
                        //}
                    }
                }
                catch (Exception e)
                {
                    log.Log(Level.SEVERE, e.Message);
                }
            }
            else
            {
                //VA073_ Module is Installed

                sql = "SELECT pl.m_product_id, p.c_project_id,p.C_Currency_ID,pl.c_projectline_id, pl.plannedqty,pl.C_UOM_ID," +
                      "(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) AS Price,pl.M_AttributeSetInstance_ID " +
                      " FROM C_Project p " +
                      "INNER JOIN C_ProjectLine pl ON p.C_Project_ID = pl.C_Project_ID" +
                      " WHERE p.c_order_id IS NULL AND p.ref_order_id IS NULL AND c_period_id = " + C_Period_ID + " AND p.AD_Org_ID = " + mf.GetAD_Org_ID() +
                      " AND C_ProjectLine_ID NOT IN (SELECT C_ProjectLine_ID FROM va073_masterforecastlinedetail WHERE " +
                      "AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_Period_ID=" + C_Period_ID + ") AND NVL(pl.M_Product_ID,0)>0 ";


                sql = MRole.GetDefault(GetCtx()).AddAccessSQL(sql, "C_Project", true, true); // fully qualified - RO

                dsOpp = new DataSet();
                dsOpp = DB.ExecuteDataset(sql, null, mf.Get_Trx());
                if (dsOpp != null && dsOpp.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < dsOpp.Tables[0].Rows.Count; i++)
                    {
                        //Create MasterForecastline
                        mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]), 0, 0, 0);
                        if (!mfLine.Save())
                        {
                            ValueNamePair vp = VLogger.RetrieveError();
                            if (vp != null)
                            {
                                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName());
                            }
                            else
                            {
                                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved"));
                            }
                        }
                        else
                        {
                            LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0)+10  FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(), null, mf.Get_Trx()));

                            //Conversion from BaseUOM to UOM on Project Line
                            OppQty = MUOMConversion.ConvertProductFrom(mf.GetCtx(), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]),
                                                                       Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["plannedqty"]));
                            if (OppQty == null)
                            {
                                OppQty = Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["plannedqty"]);
                            }

                            //Convert Line Amount as per Currency Defined ON  Master Forecast
                            ConvertedAmt = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["Price"]),
                                                                   Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_Currency_ID"]), Currency,
                                                                   Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")),
                                                                   Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID());

                            //Create Product Line Details
                            po = GenerateProductLineDetails(mfLine, LineNo, 0, 0, Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_Project_ID"]),
                                                            Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_ProjectLine_ID"]), 0, 0,
                                                            C_Period_ID, Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]),
                                                            OppQty, ConvertedAmt,
                                                            Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]));
                            if (!po.Save())
                            {
                                ValueNamePair vp = VLogger.RetrieveError();
                                if (vp != null)
                                {
                                    log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ProjectLine " + Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_ProjectLine_ID"]) + vp.GetValue() + " - " + vp.GetName());
                                }
                                else
                                {
                                    log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ProjectLine " + Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_ProjectLine_ID"]));
                                }
                            }
                            else
                            {
                                Count++;
                                LineNo += 10;
                                //Update quantities AND price at Product line
                                sql = "UPDATE c_masterforecastline SET " +
                                      "ForcastQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Forecast_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      "OppQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Project_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      "VA073_SalesOrderQty =(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Order_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      "TotalQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE  c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + ") , " +
                                      "Price= (Round((SELECT NVL(SUM(price),0)/ NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      StdPrecision + ")), " +
                                      "PlannedRevenue =(ROUND((SELECT SUM(price) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + ")," + StdPrecision + "))" +
                                      " WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID();

                                DB.ExecuteQuery(sql, null, mf.Get_Trx());
                            }
                        }
                    }
                }
                else
                {
                    log.Log(Level.INFO, Msg.GetMsg(GetCtx(), "NoRecordFoundOpportunity"));
                }
            }
            return(Count);
        }
Beispiel #31
0
        public DocAtions GetActions(int AD_Table_ID, int Record_ID, string docStatus, bool processing, string orderType, bool isSOTrx, string docAction, string tableName, List <string> _values, List <string> _names)
        {
            DocAtions action = new DocAtions();

            string[] options  = null;
            int      index    = 0;
            string   defaultV = "";

            action.DocStatus = docStatus;

            VLogger.Get().Fine("DocStatus=" + docStatus
                               + ", DocAction=" + docAction + ", OrderType=" + orderType
                               + ", IsSOTrx=" + isSOTrx + ", Processing=" + processing
                               + ", AD_Table_ID=" + AD_Table_ID + ", Record_ID=" + Record_ID);
            options = new String[_values.Count()];
            String wfStatus = MWFActivity.GetActiveInfo(ctx, AD_Table_ID, Record_ID);

            if (wfStatus != null)
            {
                VLogger.Get().SaveError("WFActiveForRecord", wfStatus);
                action.Error = "WFActiveForRecord";
                return(action);
            }

            //	Status Change
            if (!CheckStatus(tableName, Record_ID, docStatus))
            {
                VLogger.Get().SaveError("DocumentStatusChanged", "");
                action.Error = "DocumentStatusChanged";
                return(action);
            }
            // if (processing != null)
            {
                bool locked = "Y".Equals(processing);
                if (!locked && processing.GetType() == typeof(Boolean))
                {
                    locked = ((Boolean)processing);
                }
                // do not show Unlock action on Production execution
                if (locked && !(AD_Table_ID == ViennaAdvantage.Model.X_VAMFG_M_WrkOdrTransaction.Table_ID))
                {
                    options[index++] = DocumentEngine.ACTION_UNLOCK;
                }
            }

            //	Approval required           ..  NA
            if (docStatus.Equals(DocumentEngine.STATUS_NOTAPPROVED))
            {
                options[index++] = DocumentEngine.ACTION_PREPARE;
                options[index++] = DocumentEngine.ACTION_VOID;
            }
            //	Draft/Invalid				..  DR/IN
            else if (docStatus.Equals(DocumentEngine.STATUS_DRAFTED) ||
                     docStatus.Equals(DocumentEngine.STATUS_INVALID))
            {
                options[index++] = DocumentEngine.ACTION_COMPLETE;
                //	options[index++] = DocumentEngine.ACTION_Prepare;
                options[index++] = DocumentEngine.ACTION_VOID;
            }
            //	In Process                  ..  IP
            else if (docStatus.Equals(DocumentEngine.STATUS_INPROGRESS) ||
                     docStatus.Equals(DocumentEngine.STATUS_APPROVED))
            {
                options[index++] = DocumentEngine.ACTION_COMPLETE;
                options[index++] = DocumentEngine.ACTION_VOID;
            }
            //	Complete                    ..  CO
            else if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
            {
                options[index++] = DocumentEngine.ACTION_CLOSE;
            }
            //	Waiting Payment
            else if (docStatus.Equals(DocumentEngine.STATUS_WAITINGPAYMENT) ||
                     docStatus.Equals(DocumentEngine.STATUS_WAITINGCONFIRMATION))
            {
                options[index++] = DocumentEngine.ACTION_VOID;
                options[index++] = DocumentEngine.ACTION_PREPARE;
            }
            //	Closed, Voided, REversed    ..  CL/VO/RE
            else if (docStatus.Equals(DocumentEngine.STATUS_CLOSED) ||
                     docStatus.Equals(DocumentEngine.STATUS_VOIDED) ||
                     docStatus.Equals(DocumentEngine.STATUS_REVERSED))
            {
                return(action);
            }

            int  refIndex        = index;
            bool indexFromModule = true;

            GetActionFromModuleClass(AD_Table_ID, docStatus, out index, options);

            if (index == 0)
            {
                index           = refIndex;
                indexFromModule = false;
            }

            /********************
             *  Order
             */
            if (AD_Table_ID == MOrder.Table_ID)
            {
                //	Draft                       ..  DR/IP/IN
                if (docStatus.Equals(DocumentEngine.STATUS_DRAFTED) ||
                    docStatus.Equals(DocumentEngine.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocumentEngine.STATUS_INVALID))
                {
                    options[index++] = DocumentEngine.ACTION_PREPARE;

                    //JID_0213: Close option should not be visible before doc status is completed in doc process.
                    //options[index++] = DocumentEngine.ACTION_CLOSE;

                    //	Draft Sales Order Quote/Proposal - Process
                    if (isSOTrx &&
                        ("OB".Equals(orderType) || "ON".Equals(orderType)))
                    {
                        docAction = DocumentEngine.ACTION_PREPARE;
                    }
                }
                //	Complete                    ..  CO
                else if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REACTIVATE;
                }
                else if (docStatus.Equals(DocumentEngine.STATUS_WAITINGPAYMENT))
                {
                    options[index++] = DocumentEngine.ACTION_REACTIVATE;
                    options[index++] = DocumentEngine.ACTION_CLOSE;
                }
            }

            /********************
             *  Shipment
             */
            else if (AD_Table_ID == MInOut.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  Invoice
             */
            else if (AD_Table_ID == MInvoice.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  Payment
             */
            else if (AD_Table_ID == MPayment.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    //options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  GL Journal
             */
            else if (AD_Table_ID == MJournal.Table_ID || AD_Table_ID == MJournalBatch.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                    //options[index++] = DocumentEngine.ACTION_REVERSE_ACCRUAL;
                }
            }

            /********************
             *  Allocation
             */
            else if (AD_Table_ID == MAllocationHdr.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // options[index++] = DocumentEngine.ACTION_VOID;
                    options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                }
            }

            /********************
             *  Bank Statement
             */
            else if (AD_Table_ID == MBankStatement.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    options[index++] = DocumentEngine.ACTION_VOID;
                }
            }

            /********************
             *  Inventory Movement, Physical Inventory
             */
            else if (AD_Table_ID == MMovement.Table_ID ||
                     AD_Table_ID == MInventory.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // SI_0622 : not to show VOID and REVERSE_CORRECT action on Physical Inventory
                    bool isPhysicalInventory = false;
                    if (AD_Table_ID == MInventory.Table_ID)
                    {
                        MInventory inventory = MInventory.Get(ctx, Record_ID);
                        isPhysicalInventory = !inventory.IsInternalUse();
                    }
                    if (!isPhysicalInventory)
                    {
                        //options[index++] = DocumentEngine.ACTION_VOID;
                        options[index++] = DocumentEngine.ACTION_REVERSE_CORRECT;
                    }
                }
            }

            // Added By Arpit
            else if (AD_Table_ID == MMovementConfirm.Table_ID)
            {
                //	Complete                    ..  CO
                if (docStatus.Equals(DocumentEngine.STATUS_COMPLETED))
                {
                    // SI_0630 : System should not allow to void the Move confirmation after its completion
                    //options[index++] = DocumentEngine.ACTION_VOID;
                }
            }
            //End

            //    /********************
            //*  Warehouse Task  New Add by raghu 11 april,2011
            //*/
            //    else if (AD_Table_ID == X_M_WarehouseTask.Table_ID
            //        || AD_Table_ID == X_M_TaskList.Table_ID)
            //    {
            //        //	Draft                       ..  DR/IP/IN
            //        if (docStatus.Equals(DocActionVariables.STATUS_DRAFTED)
            //            || docStatus.Equals(DocActionVariables.STATUS_INPROGRESS)
            //            || docStatus.Equals(DocActionVariables.STATUS_INVALID))
            //        {
            //            options[index++] = DocActionVariables.ACTION_PREPARE;
            //        }
            //        //	Complete                    ..  CO
            //        else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
            //        {
            //            options[index++] = DocActionVariables.ACTION_VOID;
            //            options[index++] = DocActionVariables.ACTION_REVERSE_CORRECT;
            //        }
            //    }

            /********************
             *  Work Order New Add by raghu 11 april,2011
             */
            else if (AD_Table_ID == ViennaAdvantage.Model.X_VAMFG_M_WorkOrder.Table_ID)
            {
                //	Draft                       ..  DR/IP/IN
                if (docStatus.Equals(DocActionVariables.STATUS_DRAFTED) ||
                    docStatus.Equals(DocActionVariables.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocActionVariables.STATUS_INVALID))
                {
                    options[index++] = DocActionVariables.ACTION_PREPARE;
                }
                //	Complete                    ..  CO
                else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
                {
                    //options[index++] = DocActionVariables.ACTION_VOID;
                    options[index++] = DocActionVariables.ACTION_REACTIVATE;
                }
            }

            /********************
             *  Work Order Transaction New Add by raghu 11 april,2011
             */
            else if (AD_Table_ID == ViennaAdvantage.Model.X_VAMFG_M_WrkOdrTransaction.Table_ID)
            {
                //	Draft                       ..  DR/IP/IN
                if (docStatus.Equals(DocActionVariables.STATUS_DRAFTED) ||
                    docStatus.Equals(DocActionVariables.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocActionVariables.STATUS_INPROGRESS) ||
                    docStatus.Equals(DocActionVariables.STATUS_INVALID))
                {
                    options[index++] = DocActionVariables.ACTION_PREPARE;
                }
                //	Complete                    ..  CO
                else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
                {
                    //options[index++] = DocActionVariables.ACTION_VOID;
                    options[index++] = DocActionVariables.ACTION_REVERSE_CORRECT;
                }
            }

            /* Obsolete Inventory New add by Amit 24-May-2016 */
            //else if (tableName == "VA024_ObsoleteInventory")
            //{
            //    // DR/IN
            //    if (docStatus.Equals(DocumentEngine.STATUS_DRAFTED)
            //        || docStatus.Equals(DocumentEngine.STATUS_INVALID))
            //    {
            //        options[index++] = DocumentEngine.ACTION_COMPLETE;
            //        options[index++] = DocumentEngine.ACTION_VOID;
            //    }
            //    //	Complete
            //    else if (docStatus.Equals(DocActionVariables.STATUS_COMPLETED))
            //    {
            //        options[index++] = DocActionVariables.ACTION_VOID;
            //        options[index++] = DocActionVariables.ACTION_REVERSE_CORRECT;
            //    }
            //}

            /***For Primary thread***/
            ///**
            // *	Fill actionCombo
            // */
            //for (int i = 0; i < index; i++)
            //{
            //    //	Serach for option and add it
            //    bool added = false;
            //    for (int j = 0; j < _values.Length && !added; j++)
            //        if (options[i].Equals(_values[j]))
            //        {
            //            //actionCombo.addItem(_names[j]);
            //            vcmbAction.Items.Add(_names[j]);
            //            added = true;
            //        }
            //}

            //	setDefault
            if (docAction.Equals("--"))         //	If None, suggest closing
            {
                docAction = DocumentEngine.ACTION_CLOSE;
            }

            // check applied to display Document Actions on Transactions based on the document type
            // and the setting "Check Document Action Access" on Role window
            int    C_DocType_ID       = 0;
            int    C_DocTypeTarget_ID = 0;
            MTable table = MTable.Get(ctx, AD_Table_ID);
            PO     po    = table.GetPO(ctx, Record_ID, null);

            if (Util.GetValueOfInt(po.Get_Value("C_DocType_ID")) > 0)
            {
                C_DocType_ID = Util.GetValueOfInt(po.Get_Value("C_DocType_ID"));
            }
            if (Util.GetValueOfInt(po.Get_Value("C_DocTypeTarget_ID")) > 0)
            {
                C_DocTypeTarget_ID = Util.GetValueOfInt(po.Get_Value("C_DocTypeTarget_ID"));
                C_DocType_ID       = C_DocTypeTarget_ID;
            }

            if (C_DocType_ID > 0)
            {
                String[] docActionHolder = new String[] { docAction };
                if (po is DocOptions)
                {
                    index = ((DocOptions)po).customizeValidActions(docStatus, processing, orderType, isSOTrx ? "Y" : "N",
                                                                   AD_Table_ID, docActionHolder, options, index);
                }

                options = DocumentEngine.checkActionAccess(ctx, ctx.GetAD_Client_ID(), ctx.GetAD_Role_ID(), C_DocType_ID, options, ref index);
            }

            for (int i = 0; i < _values.Count() && defaultV.Equals(""); i++)
            {
                if (docAction.Equals(_values[i]))
                {
                    defaultV = _names[i];
                }
            }


            action.Options = options.ToList();
            if (indexFromModule)
            {
                action.Index = index + 1;
            }
            else
            {
                action.Index = index;
            }
            action.DefaultV = defaultV;

            return(action);

            /***For Primary thread***/
            //if (!defaultV.Equals(""))
            //{
            //    //vcmbAction.SelectedValue = defaultV;
            //    vcmbAction.SelectedItem = defaultV;
            //}
        }
        /// <SUMmary>
        /// Team Forecast Products
        /// </SUMmary>
        /// <returns>No of lines created</returns>
        private int TeamForecastProduct()
        {
            sql = @"SELECT fl.M_Product_ID,fl.M_AttributeSetInstance_ID,fl.qtyentered,fl.BaseQty,f.C_Forecast_ID,
                    C_ForecastLine_ID,f.C_Period_ID,fl.C_UOM_ID,NVL(pricestd,0) AS Price,f.C_Currency_ID
                    FROM C_Forecast f " +
                  " INNER JOIN C_Forecastline fl ON fl.c_forecast_id = f.c_forecast_id " +
                  " WHERE f.c_period_id = " + C_Period_ID + " AND f.AD_Org_ID = " + mf.GetAD_Org_ID() +
                  " AND f.isactive = 'Y' AND f.processed = 'Y'" +
                  " AND C_ForecastLine_ID NOT IN (SELECT C_ForecastLine_ID FROM VA073_MasterForecastlinedetail WHERE " +
                  "AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_Period_ID=" + C_Period_ID + ") AND NVL(fl.M_Product_ID,0)>0 ";

            sql = MRole.GetDefault(mf.GetCtx()).AddAccessSQL(sql, "C_Forecast", true, true); // fully qualified - RO

            dsForecast = new DataSet();
            dsForecast = DB.ExecuteDataset(sql, null, mf.Get_Trx());
            if (dsForecast != null && dsForecast.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dsForecast.Tables[0].Rows.Count; i++)
                {
                    //Create MasterForecastLine
                    mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]), 0, 0, 0);
                    if (!mfLine.Save())
                    {
                        ValueNamePair vp = VLogger.RetrieveError();
                        if (vp != null)
                        {
                            log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName());
                        }
                        else
                        {
                            log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved"));
                        }
                    }
                    else
                    {
                        LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0)+10  FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(), null, mf.Get_Trx()));
                        //Convert Line Amount as per Currency Defined ON  Master Forecast
                        ConvertedAmt = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsForecast.Tables[0].Rows[i]["Price"]),
                                                               Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_Currency_ID"]), Currency,
                                                               Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")),
                                                               Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID());

                        //Create Product Line Details
                        po = GenerateProductLineDetails(mfLine, LineNo, 0, 0, 0, 0, Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_Forecast_ID"]),
                                                        Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_ForecastLine_ID"]),
                                                        Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_Period_ID"]), mfLine.GetC_UOM_ID(),
                                                        Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfDecimal(dsForecast.Tables[0].Rows[i]["qtyentered"]),
                                                        ConvertedAmt, Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]));
                        if (!po.Save())
                        {
                            ValueNamePair vp = VLogger.RetrieveError();
                            if (vp != null)
                            {
                                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ForecastLine " + Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_ForecastLine_ID"]) + " " + vp.GetValue() + " - " + vp.GetName());
                            }
                            else
                            {
                                log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ForecastLine " + Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_ForecastLine_ID"]));
                            }
                        }
                        else
                        {
                            //Update quantities AND Price at Product line
                            Count++;
                            LineNo += 10;
                            sql     = "UPDATE c_masterforecastline SET " +
                                      "ForcastQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Forecast_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      "OppQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Project_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      "VA073_SalesOrderQty =(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Order_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      "TotalQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE  c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + ") , " +
                                      "Price= (Round((SELECT NVL(SUM(price),0)/ NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " +
                                      StdPrecision + ")), " +
                                      "PlannedRevenue =(ROUND((SELECT SUM(price) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + ")," + StdPrecision + "))" +
                                      " WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID();

                            DB.ExecuteQuery(sql, null, mf.Get_Trx());
                        }
                    }
                }
            }
            else
            {
                log.Log(Level.INFO, Msg.GetMsg(GetCtx(), "NoRecordFoundForecast"));
            }
            return(Count);
        }
Beispiel #33
0
 public POVM() : base()
 {
     TheEntity         = new PO();
     TheEntity.POlines = new List <POline>();
 }
Beispiel #34
0
        public PO GetPO(Ctx ctx, int Record_ID, Trx trxName, bool isNew)
        {
            //return GetPO(ctx, Record_ID, trxName, true);
            string tableName = GetTableName();

            if (Record_ID != 0 && !IsSingleKey())
            {
                log.Log(Level.WARNING, "(id) - Multi-Key " + tableName);
                return(null);

                //Updateby--Raghu
                //to run work flow with virtual M_ or X_ classes
                //log.Log(Level.INFO, "Using GenericPO for " + tableName);
                //GenericPO po = new GenericPO(tableName, ctx, Record_ID, trxName);
                //return po;
            }

            Type className = GetClass(tableName);

            if (className == null)
            {
                //log.log(Level.WARNING, "(id) - Class not found for " + tableName);
                //to run work flow with virtual M_ or X_ classes
                log.Log(Level.INFO, "Using GenericPO for " + tableName);
                GenericPO po = new GenericPO(tableName, ctx, Record_ID, trxName);
                return(po);
            }
            bool errorLogged = false;

            try
            {
                ConstructorInfo constructor = null;
                try
                {
                    constructor = className.GetConstructor(new Type[] { typeof(Ctx), typeof(int), typeof(Trx) });
                }
                catch (Exception e)
                {
                    log.Warning("No transaction Constructor for " + className.FullName + " (" + e.ToString() + ")");
                }

                if (constructor != null)
                {
                    PO po = (PO)constructor.Invoke(new object[] { ctx, Record_ID, trxName });
                    //	Load record 0 - valid for System/Client/Org/Role/User
                    if (!isNew && Record_ID == 0)
                    {
                        po.Load(trxName);
                    }
                    //	Check if loaded correctly
                    if (po != null && po.Get_ID() != Record_ID && IsSingleKey())
                    {
                        // Common.//ErrorLog.FillErrorLog("MTable", "", po.Get_TableName() + "_ID=" + po.Get_ID() + " <> requested=" + Record_ID, VAdvantage.Framework.Message.MessageType.INFORMATION);
                        return(null);
                    }
                    return(po);
                }
                else
                {
                    throw new Exception("No Std Constructor");
                }
            }
            catch (Exception ex1)
            {
                log.Severe(ex1.ToString());
                //exception handling
            }
            if (!errorLogged)
            {
                //log.log(Level.SEVERE, "(id) - Not found - Table=" + tableName
                //    + ", Record_ID=" + Record_ID);
            }
            return(null);
        }
 public static bool insertSupplierInvoice(APCEntities APCContext, string supplierOriNo, decimal paymentDue, DateTime dueDate, PO po)
 {
     if (supplierOriNo.Trim() != "")
     {
         SupplierInvoice supplierInvoice = new SupplierInvoice();
         supplierInvoice.SupplierOriNo = supplierOriNo;
         supplierInvoice.PaymentDue = paymentDue;
         supplierInvoice.DueDate = dueDate;
         supplierInvoice.PO = po;
         supplierInvoice.Paid = false;
         APCContext.AddToSupplierInvoice(supplierInvoice);
         APCContext.SaveChanges();
         return true;
     }
     else
         return false;
 }
Beispiel #36
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            int id = 0;

            int.TryParse(tbId.Text, out id);
            if (id != 0)
            {
                Invoice currentInvoice = BLInvoice.GetInvoiceById(APCContext, id);
                if (currentInvoice != null)
                {
                    decimal paymentDue = 0;
                    if (decimal.TryParse(tbPaymentDue.Text, out paymentDue))
                    {
                        if (calDueDate.Value != null)
                        {
                            //if (ddlPO.SelectedValue != null)
                            //{
                            if (ddlProject.SelectedValue != null)
                            {
                                PO      selectedPO      = BLPO.GetPOById(APCContext, int.Parse(ddlPO.SelectedValue.ToString()));
                                Project selectedProject = BLProject.GetProjectById(APCContext, int.Parse(ddlProject.SelectedValue.ToString()));

                                currentInvoice.TotalDue   = paymentDue;
                                currentInvoice.DueDate    = calDueDate.Value;
                                currentInvoice.ScannedDoc = tbScannedDoc.Text;
                                currentInvoice.Project    = selectedProject;
                                APCContext.SaveChanges();

                                DeleteInvoicePO(currentInvoice);
                                InsertInvoicePO(currentInvoice);

                                deleteInvoice_Product(currentInvoice);
                                insertInvoice_Product(currentInvoice);

                                MessageBox.Show("Invoice Details Successfully Updated");
                                ClearContent();
                            }
                            else
                            {
                                MessageBox.Show("Please select the associated Project");
                            }
                            //}
                            //else
                            //    MessageBox.Show("Please select the associated PO Number");
                        }
                        else
                        {
                            MessageBox.Show("Please specify a correct due date");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please specify correct amount of Payment Due");
                    }
                }
                else
                {
                    MessageBox.Show("Invoice Id not found");
                }
            }
            else
            {
                MessageBox.Show("Invoice Id not found");
            }
        }
        /**
         *  After Save
         *	@param newRecord new record
         *	@param success success
         *	@return success
         */
        protected override Boolean AfterSave(Boolean newRecord, Boolean success)
        {
            int           _client_ID = 0;
            StringBuilder _sql       = new StringBuilder();

            //_sql.Append("Select count(*) from  ad_table where tablename like 'FRPT_BP_Group_Acct'");
            _sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_BP_Group_Acct')  AND OWNER LIKE '" + DB.GetSchema() + "'");
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                _sql.Clear();
                _sql.Append("SELECT L.VALUE FROM AD_REF_LIST L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where r.name='FRPT_RelatedTo' and l.name='Customer'");
                var relatedtoCustomer = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));
                _sql.Clear();
                _sql.Append("Select L.Value From Ad_Ref_List L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where r.name='FRPT_RelatedTo' and l.name='Vendor'");
                var relatedtoVendor = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));
                _sql.Clear();
                _sql.Append("Select L.Value From Ad_Ref_List L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where r.name='FRPT_RelatedTo' and l.name='Employee'");
                var relatedtoEmployee = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));

                PO gpact = null;
                _client_ID = GetAD_Client_ID();
                _sql.Clear();
                _sql.Append("select C_AcctSchema_ID from C_AcctSchema where AD_CLIENT_ID=" + _client_ID);
                DataSet ds3 = new DataSet();
                ds3 = DB.ExecuteDataset(_sql.ToString(), null);
                if (ds3 != null && ds3.Tables[0].Rows.Count > 0)
                {
                    for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                    {
                        int _AcctSchema_ID = Util.GetValueOfInt(ds3.Tables[0].Rows[k]["C_AcctSchema_ID"]);
                        _sql.Clear();
                        _sql.Append("Select Frpt_Acctdefault_Id,C_Validcombination_Id,Frpt_Relatedto From Frpt_Acctschema_Default Where ISACTIVE='Y' AND AD_CLIENT_ID=" + _client_ID + "AND C_Acctschema_Id=" + _AcctSchema_ID);
                        DataSet ds = new DataSet();
                        ds = DB.ExecuteDataset(_sql.ToString(), null);
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                //DataSet ds2 = new DataSet();
                                string _relatedTo = ds.Tables[0].Rows[i]["Frpt_Relatedto"].ToString();
                                if (_relatedTo != "")
                                {
                                    if (_relatedTo == relatedtoCustomer || _relatedTo == relatedtoEmployee || _relatedTo == relatedtoVendor)
                                    {
                                        _sql.Clear();
                                        //_sql.Append("Select Bp.C_BP_Group_ID,ca.Frpt_Acctdefault_Id From C_BP_Group Bp Left Join FRPT_BP_Group_Acct ca On Bp.C_BP_Group_ID=ca.C_BP_Group_ID And ca.Frpt_Acctdefault_Id=" + ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"] + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + _client_ID);
                                        _sql.Append("Select COUNT(*) From C_BP_Group Bp Left Join FRPT_BP_Group_Acct ca On Bp.C_BP_Group_ID=ca.C_BP_Group_ID And ca.Frpt_Acctdefault_Id=" + ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"] + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + _client_ID + " AND ca.C_Validcombination_Id = " + Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]) + " AND Bp.C_BP_Group_ID = " + GetC_BP_Group_ID());
                                        int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                        // ds2 = DB.ExecuteDataset(_sql.ToString(), null);
                                        //if (ds2 != null && ds2.Tables[0].Rows.Count > 0)
                                        //{
                                        //    for (int j = 0; j < ds2.Tables[0].Rows.Count; j++)
                                        //    {
                                        //        int value = Util.GetValueOfInt(ds2.Tables[0].Rows[j]["Frpt_Acctdefault_Id"]);
                                        //        if (value == 0)
                                        //        {
                                        //gpact = new X_FRPT_BP_Group_Acct(GetCtx(), 0, null);
                                        if (recordFound == 0)
                                        {
                                            gpact = MTable.GetPO(GetCtx(), "FRPT_BP_Group_Acct", 0, null);
                                            //gpact.Set_ValueNoCheck("C_BP_Group_ID", Util.GetValueOfInt(ds2.Tables[0].Rows[j]["C_BP_Group_ID"]));
                                            gpact.Set_ValueNoCheck("C_BP_Group_ID", Util.GetValueOfInt(GetC_BP_Group_ID()));
                                            gpact.Set_ValueNoCheck("AD_Org_ID", 0);
                                            gpact.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                                            gpact.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]));
                                            gpact.Set_ValueNoCheck("C_AcctSchema_ID", _AcctSchema_ID);
                                            if (!gpact.Save())
                                            {
                                            }
                                        }
                                        //}
                                        //}
                                        //}
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                object table = DB.ExecuteScalar("SELECT count(*) from AD_Table WHERE TableName='C_BP_Group_Acct'");
                if (table == null || table == DBNull.Value || table == "" || Convert.ToInt16(table) == 0)
                {
                    return(success);
                }

                if (newRecord & success && (String.IsNullOrEmpty(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) || Util.GetValueOfString(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) == "Y"))
                {
                    success = Insert_Accounting("C_BP_Group_Acct", "C_AcctSchema_Default", null);

                    //Karan. work done to show message if data not saved in accounting tab. but will save data in current tab.
                    // Before this, data was being saved but giving message "record not saved".
                    if (!success)
                    {
                        log.SaveWarning("AcctNotSaved", "");
                        return(true);
                    }
                }
            }
            return(success);
        }
Beispiel #38
0
 public void GoWork(PO a, Naboroperaciy b)
 {
     Console.WriteLine(Devname + " Rabotaet nad " + a.Name + " Dobovlyaet tuda " + b.Nabor);
 }
        /// <summary>
        /// After save logic for asset
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="success"></param>
        /// <returns></returns>
        protected override bool AfterSave(bool newRecord, bool success)
        {
            //Cost Code Commented - As not required on Asset Save
            //if (newRecord)
            //{
            //    UpdateAssetCost();
            //}

            // create default Account
            StringBuilder _sql = new StringBuilder("");

            // check table exist or not
            //_sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_Asset_Group_Acct')  AND OWNER LIKE '" + DB.GetSchema() + "'");
            _sql.Append(DBFunctionCollection.CheckTableExistence(DB.GetSchema(), "FRPT_Asset_Group_Acct"));
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                PO  obj          = null;
                int assetId      = GetA_Asset_ID();
                int assetGroupId = GetA_Asset_Group_ID();
                // get related to value agaisnt asset = 75
                string sql = "SELECT L.VALUE FROM AD_REF_LIST L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where   r.name='FRPT_RelatedTo' and l.name='Asset'";
                string _RelatedToProduct = Convert.ToString(DB.ExecuteScalar(sql));

                _sql.Clear();
                _sql.Append("Select Count(*) From FRPT_Asset_Acct   where A_Asset_ID=" + assetId + " AND IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID());
                int value = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));
                if (value < 1)
                {
                    _sql.Clear();
                    _sql.Append(@"Select  PCA.c_acctschema_id, PCA.c_validcombination_id, PCA.frpt_acctdefault_id " +
                                " From FRPT_Asset_Group_Acct PCA " +
                                " inner join frpt_acctdefault ACC ON acc.frpt_acctdefault_id= PCA.frpt_acctdefault_id " +
                                " where PCA.A_Asset_Group_ID=" + assetGroupId +
                                " and acc.frpt_relatedto='" + _RelatedToProduct +
                                "' AND PCA.IsActive = 'Y' AND PCA.AD_Client_ID = " + GetAD_Client_ID());

                    DataSet ds = DB.ExecuteDataset(_sql.ToString());
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            obj = MTable.GetPO(GetCtx(), "FRPT_Asset_Acct", 0, null);
                            obj.Set_ValueNoCheck("AD_Org_ID", 0);
                            obj.Set_ValueNoCheck("A_Asset_ID", assetId);
                            obj.Set_ValueNoCheck("C_AcctSchema_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_AcctSchema_ID"]));
                            obj.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_ValidCombination_ID"]));
                            obj.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                            if (!obj.Save())
                            {
                                ValueNamePair pp = VLogger.RetrieveError();
                                _log.Log(Level.SEVERE, "Could Not create FRPT_Asset_Acct. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName());
                            }
                        }
                    }
                }
            }

            return(true);
        }
Beispiel #40
0
        /*******************************************************************************************************/
        #region SUBMISSION

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (isInputValid())
            {
                string productDescription = "";
                Guid   poID = Guid.NewGuid();

                //compile data
                List <POItem>        POItems        = new List <POItem>();
                List <SaleOrderItem> saleOrderItems = new List <SaleOrderItem>();
                foreach (DataGridViewRow row in gridPOItems.Rows)
                {
                    if (isValidProductName(row) && isValidQty(row))
                    {
                        Guid?referencedInventoryID = null;
                        if (row.Cells[col_gridPOItems_referencedInventoryID.Name].Value != null)
                        {
                            referencedInventoryID = (Guid)row.Cells[col_gridPOItems_referencedInventoryID.Name].Value;
                        }

                        productDescription = compileProductDescription(
                            row.Cells[col_gridPOItems_productName.Name].Value.ToString(),
                            row.Cells[col_gridPOItems_widthName.Name].Value.ToString(),
                            row.Cells[col_gridPOItems_gradeName.Name].Value.ToString(),
                            row.Cells[col_gridPOItems_colorName.Name].Value.ToString());

                        //add each row to list
                        if (iddl_Vendor.Enabled)
                        {
                            POItems.Add(new POItem(
                                            Guid.NewGuid(),
                                            poID,
                                            row.Index + 1,
                                            productDescription,
                                            Convert.ToDecimal(row.Cells[col_gridPOItems_qty.Name].Value),
                                            row.Cells[col_gridPOItems_unitName.Name].Value.ToString(),
                                            Convert.ToDecimal(row.Cells[col_gridPOItems_pricePerUnit.Name].Value),
                                            Util.wrapNullable <string>(row.Cells[col_gridPOItems_notes.Name].Value),
                                            referencedInventoryID));
                        }
                        else
                        {
                            saleOrderItems.Add(new SaleOrderItem(
                                                   Guid.NewGuid(),
                                                   poID,
                                                   row.Index + 1,
                                                   productDescription,
                                                   Convert.ToDecimal(row.Cells[col_gridPOItems_qty.Name].Value),
                                                   row.Cells[col_gridPOItems_unitName.Name].Value.ToString(),
                                                   Convert.ToDecimal(row.Cells[col_gridPOItems_pricePerUnit.Name].Value),
                                                   Util.wrapNullable <string>(row.Cells[col_gridPOItems_notes.Name].Value),
                                                   referencedInventoryID));
                        }
                    }
                }
                if (iddl_Vendor.Enabled && PO.submitNew(poID, (Guid)iddl_Vendor.SelectedValue, lblInfo.Text, POItems, txtNotes.Text.Trim(), dtpTarget.Value, txtPONo.Text) != null)
                {
                    Tools.displayForm(new POs.Print_Form(poID));
                    this.Close();
                }
                else if (SaleOrder.add(poID, (Guid)iddl_Customers.SelectedValue, lblInfo.Text, saleOrderItems, txtNotes.Text.Trim(), dtpTarget.Value, txtPONo.Text))
                {
                    this.Close();
                }
            }
        }
Beispiel #41
0
        public void Update(POItemDetails Details)
        {
            try
            {
                string SQL = "UPDATE tblPOItems SET " +
                             "POID					=	@POID, "+
                             "ProductID				=	@ProductID, "+
                             "ProductCode			=	@ProductCode, "+
                             "BarCode				=	@BarCode, "+
                             "Description			=	@Description, "+
                             "ProductUnitID			=	@ProductUnitID, "+
                             "ProductUnitCode		=	@ProductUnitCode, "+
                             "Quantity				=	@Quantity, "+
                             "OriginalQuantity       =   @Quantity, " +
                             "UnitCost				=	@UnitCost, "+
                             "Discount				=	@Discount, "+
                             "DiscountApplied		=	@DiscountApplied, "+
                             "DiscountType			=	@DiscountType, "+
                             "Amount					=	@Amount, "+
                             "VAT					=	@VAT, "+
                             "VatableAmount			=	@VatableAmount, "+
                             "EVAT					=	@EVAT, "+
                             "EVatableAmount			=	@EVatableAmount, "+
                             "LocalTax				=	@LocalTax, "+
                             "isVATInclusive			=	@isVATInclusive, "+
                             "VariationMatrixID		=	@VariationMatrixID, "+
                             "MatrixDescription		=	@MatrixDescription, "+
                             "ProductGroup			=	@ProductGroup, "+
                             "ProductSubGroup		=	@ProductSubGroup, "+
                             "POItemStatus			=	@POItemStatus, "+
                             "IsVatable				=	@IsVatable, "+
                             "Remarks				=	@Remarks, "+
                             "ChartOfAccountIDPurchase       = (SELECT ChartOfAccountIDPurchase FROM tblProducts WHERE ProductID = @ProductID), " +
                             "ChartOfAccountIDTaxPurchase    = (SELECT ChartOfAccountIDTaxPurchase FROM tblProducts WHERE ProductID = @ProductID), " +
                             "ChartOfAccountIDInventory      = (SELECT ChartOfAccountIDInventory FROM tblProducts WHERE ProductID = @ProductID), " +
                             "SellingPrice			=	@SellingPrice, "+
                             "SellingVAT				=	@SellingVAT, "+
                             "SellingEVAT			=	@SellingEVAT, "+
                             "SellingLocalTax		=	@SellingLocalTax, "+
                             "OldSellingPrice		=	@OldSellingPrice, "+
                             "RID		            =	@RID "+
                             "WHERE POItemID = @POItemID;";

                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = SQL;

                MySqlParameter prmPOID = new MySqlParameter("@POID", MySqlDbType.Int64);
                prmPOID.Value = Details.POID;
                cmd.Parameters.Add(prmPOID);

                MySqlParameter prmProductID = new MySqlParameter("@ProductID", MySqlDbType.Int64);
                prmProductID.Value = Details.ProductID;
                cmd.Parameters.Add(prmProductID);

                MySqlParameter prmProductCode = new MySqlParameter("@ProductCode", MySqlDbType.String);
                prmProductCode.Value = Details.ProductCode;
                cmd.Parameters.Add(prmProductCode);

                MySqlParameter prmBarCode = new MySqlParameter("@BarCode", MySqlDbType.String);
                prmBarCode.Value = Details.BarCode;
                cmd.Parameters.Add(prmBarCode);

                MySqlParameter prmDescription = new MySqlParameter("@Description", MySqlDbType.String);
                prmDescription.Value = Details.Description;
                cmd.Parameters.Add(prmDescription);

                MySqlParameter prmProductUnitID = new MySqlParameter("@ProductUnitID", MySqlDbType.Int16);
                prmProductUnitID.Value = Details.ProductUnitID;
                cmd.Parameters.Add(prmProductUnitID);

                MySqlParameter prmProductUnitCode = new MySqlParameter("@ProductUnitCode", MySqlDbType.String);
                prmProductUnitCode.Value = Details.ProductUnitCode;
                cmd.Parameters.Add(prmProductUnitCode);

                MySqlParameter prmQuantity = new MySqlParameter("@Quantity", MySqlDbType.Decimal);
                prmQuantity.Value = Details.Quantity;
                cmd.Parameters.Add(prmQuantity);

                MySqlParameter prmUnitCost = new MySqlParameter("@UnitCost", MySqlDbType.Decimal);
                prmUnitCost.Value = Details.UnitCost;
                cmd.Parameters.Add(prmUnitCost);

                MySqlParameter prmDiscount = new MySqlParameter("@Discount", MySqlDbType.Decimal);
                prmDiscount.Value = Details.Discount;
                cmd.Parameters.Add(prmDiscount);

                MySqlParameter prmDiscountApplied = new MySqlParameter("@DiscountApplied", MySqlDbType.Decimal);
                prmDiscountApplied.Value = Details.DiscountApplied;
                cmd.Parameters.Add(prmDiscountApplied);

                MySqlParameter prmDiscountType = new MySqlParameter("@DiscountType", MySqlDbType.Int16);
                prmDiscountType.Value = (int)Details.DiscountType;
                cmd.Parameters.Add(prmDiscountType);

                MySqlParameter prmAmount = new MySqlParameter("@Amount", MySqlDbType.Decimal);
                prmAmount.Value = Details.Amount;
                cmd.Parameters.Add(prmAmount);

                MySqlParameter prmVAT = new MySqlParameter("@VAT", MySqlDbType.Decimal);
                prmVAT.Value = Details.VAT;
                cmd.Parameters.Add(prmVAT);

                MySqlParameter prmVatableAmount = new MySqlParameter("@VatableAmount", MySqlDbType.Decimal);
                prmVatableAmount.Value = Details.VatableAmount;
                cmd.Parameters.Add(prmVatableAmount);

                MySqlParameter prmEVAT = new MySqlParameter("@EVAT", MySqlDbType.Decimal);
                prmEVAT.Value = Details.EVAT;
                cmd.Parameters.Add(prmEVAT);

                MySqlParameter prmEVatableAmount = new MySqlParameter("@EVatableAmount", MySqlDbType.Decimal);
                prmEVatableAmount.Value = Details.EVatableAmount;
                cmd.Parameters.Add(prmEVatableAmount);

                MySqlParameter prmLocalTax = new MySqlParameter("@LocalTax", MySqlDbType.Decimal);
                prmLocalTax.Value = Details.LocalTax;
                cmd.Parameters.Add(prmLocalTax);

                MySqlParameter prmisVATInclusive = new MySqlParameter("@isVATInclusive", MySqlDbType.Int16);
                prmisVATInclusive.Value = Convert.ToInt16(Details.isVATInclusive);
                cmd.Parameters.Add(prmisVATInclusive);

                MySqlParameter prmVariationMatrixID = new MySqlParameter("@VariationMatrixID", MySqlDbType.Int64);
                prmVariationMatrixID.Value = Details.VariationMatrixID;
                cmd.Parameters.Add(prmVariationMatrixID);

                MySqlParameter prmMatrixDescription = new MySqlParameter("@MatrixDescription", MySqlDbType.String);
                prmMatrixDescription.Value = Details.MatrixDescription;
                cmd.Parameters.Add(prmMatrixDescription);

                MySqlParameter prmProductGroup = new MySqlParameter("@ProductGroup", MySqlDbType.String);
                prmProductGroup.Value = Details.ProductGroup;
                cmd.Parameters.Add(prmProductGroup);

                cmd.Parameters.AddWithValue("@ProductSubGroup", Details.ProductSubGroup);
                cmd.Parameters.AddWithValue("@POItemStatus", Details.POItemStatus.ToString("d"));
                cmd.Parameters.AddWithValue("@IsVatable", Convert.ToInt16(Details.IsVatable));
                cmd.Parameters.AddWithValue("@Remarks", Details.Remarks);
                cmd.Parameters.AddWithValue("@SellingPrice", Details.SellingPrice);
                cmd.Parameters.AddWithValue("@SellingVAT", Details.SellingVAT);
                cmd.Parameters.AddWithValue("@SellingEVAT", Details.SellingEVAT);
                cmd.Parameters.AddWithValue("@SellingLocalTax", Details.SellingLocalTax);
                cmd.Parameters.AddWithValue("@OldSellingPrice", Details.OldSellingPrice);
                cmd.Parameters.AddWithValue("@RID", Details.RID);
                cmd.Parameters.AddWithValue("@POItemID", Details.POItemID);

                base.ExecuteNonQuery(cmd);

                PO clsPO = new PO(base.Connection, base.Transaction);
                clsPO.SynchronizeAmount(Details.POID);
            }

            catch (Exception ex)
            {
                throw base.ThrowException(ex);
            }
        }
Beispiel #42
0
        /// <summary>
        /// After Save
        /// </summary>
        /// <param name="newRecord"></param>
        /// <param name="success"></param>
        /// <returns>success</returns>
        protected override Boolean AfterSave(Boolean newRecord, Boolean success)
        {
            PO            tax        = null;
            int           _client_ID = 0;
            StringBuilder _sql       = new StringBuilder();

            //_sql.Append("Select count(*) from  ad_table where tablename like 'FRPT_TaxRate_Acct'");
            _sql.Append("SELECT count(*) FROM all_objects WHERE object_type IN ('TABLE') AND (object_name)  = UPPER('FRPT_TaxRate_Acct')  AND OWNER LIKE '" + DB.GetSchema() + "'");
            int count = Util.GetValueOfInt(DB.ExecuteScalar(_sql.ToString()));

            if (count > 0)
            {
                _sql.Clear();
                _sql.Append("Select L.Value From Ad_Ref_List L inner join AD_Reference r on R.AD_REFERENCE_ID=L.AD_REFERENCE_ID where r.name='FRPT_RelatedTo' and l.name='Tax Rate'");
                var relatedtoTax = Convert.ToString(DB.ExecuteScalar(_sql.ToString()));
                _client_ID = GetAD_Client_ID();
                _sql.Clear();
                _sql.Append("select C_AcctSchema_ID from C_AcctSchema where AD_CLIENT_ID=" + _client_ID);
                DataSet ds3 = new DataSet();
                ds3 = DB.ExecuteDataset(_sql.ToString(), null);
                if (ds3 != null && ds3.Tables[0].Rows.Count > 0)
                {
                    for (int k = 0; k < ds3.Tables[0].Rows.Count; k++)
                    {
                        int _AcctSchema_ID = Util.GetValueOfInt(ds3.Tables[0].Rows[k]["C_AcctSchema_ID"]);
                        _sql.Clear();
                        _sql.Append("Select Frpt_Acctdefault_Id,C_Validcombination_Id,Frpt_Relatedto From Frpt_Acctschema_Default Where ISACTIVE='Y' AND AD_CLIENT_ID=" + _client_ID + "AND C_Acctschema_Id=" + _AcctSchema_ID);
                        DataSet ds = DB.ExecuteDataset(_sql.ToString(), null);
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                string _relatedTo = ds.Tables[0].Rows[i]["Frpt_Relatedto"].ToString();
                                if (_relatedTo != "" && (_relatedTo == relatedtoTax))
                                {
                                    _sql.Clear();
                                    _sql.Append("Select COUNT(*) From C_Tax Bp Left Join FRPT_TaxRate_Acct ca On Bp.C_Tax_ID=ca.C_Tax_ID And ca.Frpt_Acctdefault_Id=" + ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"] + " WHERE Bp.IsActive='Y' AND Bp.AD_Client_ID=" + _client_ID + " AND ca.C_Validcombination_Id = " + Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]) + " AND Bp.C_Tax_ID = " + GetC_Tax_ID());
                                    int recordFound = Convert.ToInt32(DB.ExecuteScalar(_sql.ToString(), null, Get_Trx()));
                                    if (recordFound == 0)
                                    {
                                        tax = MTable.GetPO(GetCtx(), "FRPT_TaxRate_Acct", 0, null);
                                        tax.Set_ValueNoCheck("AD_Org_ID", 0);
                                        tax.Set_ValueNoCheck("C_Tax_ID", Util.GetValueOfInt(GetC_Tax_ID()));
                                        tax.Set_ValueNoCheck("FRPT_AcctDefault_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["FRPT_AcctDefault_ID"]));
                                        tax.Set_ValueNoCheck("C_ValidCombination_ID", Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Validcombination_Id"]));
                                        tax.Set_ValueNoCheck("C_AcctSchema_ID", _AcctSchema_ID);
                                        if (!tax.Save())
                                        {
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (newRecord & success && (String.IsNullOrEmpty(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) || Util.GetValueOfString(GetCtx().GetContext("#DEFAULT_ACCOUNTING_APPLICABLE")) == "Y"))
            {
                bool sucs = Insert_Accounting("C_Tax_Acct", "C_AcctSchema_Default", null);
                //Karan. work done to show message if data not saved in accounting tab. but will save data in current tab.
                // Before this, data was being saved but giving message "record not saved".
                if (!sucs)
                {
                    log.SaveWarning("AcctNotSaved", "");
                }
            }

            return(success);
        }
Beispiel #43
0
        public long Insert(POItemDetails Details)
        {
            try
            {
                string SQL = "INSERT INTO tblPOItems (" +
                             "POID, " +
                             "ProductID, " +
                             "ProductCode, " +
                             "BarCode, " +
                             "Description, " +
                             "ProductUnitID, " +
                             "ProductUnitCode, " +
                             "Quantity, " +
                             "OriginalQuantity, " +
                             "UnitCost, " +
                             "Discount, " +
                             "DiscountApplied, " +
                             "DiscountType, " +
                             "Amount, " +
                             "VAT, " +
                             "VatableAmount, " +
                             "EVAT, " +
                             "EVatableAmount, " +
                             "LocalTax, " +
                             "isVATInclusive, " +
                             "VariationMatrixID, " +
                             "MatrixDescription, " +
                             "ProductGroup, " +
                             "ProductSubGroup, " +
                             "POItemStatus, " +
                             "IsVatable, " +
                             "Remarks, " +
                             "ChartOfAccountIDPurchase, " +
                             "ChartOfAccountIDTaxPurchase, " +
                             "ChartOfAccountIDInventory," +
                             "SellingPrice," +
                             "SellingVAT," +
                             "SellingEVAT," +
                             "SellingLocalTax," +
                             "OldSellingPrice," +
                             "RID" +
                             ") VALUES (" +
                             "@POID, " +
                             "@ProductID, " +
                             "@ProductCode, " +
                             "@BarCode, " +
                             "@Description, " +
                             "@ProductUnitID, " +
                             "@ProductUnitCode, " +
                             "@Quantity, " +
                             "@Quantity, " +
                             "@UnitCost, " +
                             "@Discount, " +
                             "@DiscountApplied, " +
                             "@DiscountType, " +
                             "@Amount, " +
                             "@VAT, " +
                             "@VatableAmount, " +
                             "@EVAT, " +
                             "@EVatableAmount, " +
                             "@LocalTax, " +
                             "@isVATInclusive, " +
                             "@VariationMatrixID, " +
                             "@MatrixDescription, " +
                             "@ProductGroup, " +
                             "@ProductSubGroup, " +
                             "@POItemStatus, " +
                             "@IsVatable, " +
                             "@Remarks, " +
                             "(SELECT ChartOfAccountIDPurchase FROM tblProducts WHERE ProductID = @ProductID), " +
                             "(SELECT ChartOfAccountIDTaxPurchase FROM tblProducts WHERE ProductID = @ProductID), " +
                             "(SELECT ChartOfAccountIDInventory FROM tblProducts WHERE ProductID = @ProductID)," +
                             "@SellingPrice," +
                             "@SellingVAT," +
                             "@SellingEVAT," +
                             "@SellingLocalTax," +
                             "@OldSellingPrice," +
                             "@RID" +
                             ");";

                MySqlCommand cmd = new MySqlCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = SQL;

                MySqlParameter prmPOID = new MySqlParameter("@POID", MySqlDbType.Int64);
                prmPOID.Value = Details.POID;
                cmd.Parameters.Add(prmPOID);

                MySqlParameter prmProductID = new MySqlParameter("@ProductID", MySqlDbType.Int64);
                prmProductID.Value = Details.ProductID;
                cmd.Parameters.Add(prmProductID);

                MySqlParameter prmProductCode = new MySqlParameter("@ProductCode", MySqlDbType.String);
                prmProductCode.Value = Details.ProductCode;
                cmd.Parameters.Add(prmProductCode);

                MySqlParameter prmBarCode = new MySqlParameter("@BarCode", MySqlDbType.String);
                prmBarCode.Value = Details.BarCode;
                cmd.Parameters.Add(prmBarCode);

                MySqlParameter prmDescription = new MySqlParameter("@Description", MySqlDbType.String);
                prmDescription.Value = Details.Description;
                cmd.Parameters.Add(prmDescription);

                MySqlParameter prmProductUnitID = new MySqlParameter("@ProductUnitID", MySqlDbType.Int16);
                prmProductUnitID.Value = Details.ProductUnitID;
                cmd.Parameters.Add(prmProductUnitID);

                MySqlParameter prmProductUnitCode = new MySqlParameter("@ProductUnitCode", MySqlDbType.String);
                prmProductUnitCode.Value = Details.ProductUnitCode;
                cmd.Parameters.Add(prmProductUnitCode);

                MySqlParameter prmQuantity = new MySqlParameter("@Quantity", MySqlDbType.Decimal);
                prmQuantity.Value = Details.Quantity;
                cmd.Parameters.Add(prmQuantity);

                MySqlParameter prmUnitCost = new MySqlParameter("@UnitCost", MySqlDbType.Decimal);
                prmUnitCost.Value = Details.UnitCost;
                cmd.Parameters.Add(prmUnitCost);

                MySqlParameter prmDiscount = new MySqlParameter("@Discount", MySqlDbType.Decimal);
                prmDiscount.Value = Details.Discount;
                cmd.Parameters.Add(prmDiscount);

                MySqlParameter prmDiscountApplied = new MySqlParameter("@DiscountApplied", MySqlDbType.Decimal);
                prmDiscountApplied.Value = Details.DiscountApplied;
                cmd.Parameters.Add(prmDiscountApplied);

                MySqlParameter prmDiscountType = new MySqlParameter("@DiscountType", MySqlDbType.Int16);
                prmDiscountType.Value = (int)Details.DiscountType;
                cmd.Parameters.Add(prmDiscountType);

                MySqlParameter prmAmount = new MySqlParameter("@Amount", MySqlDbType.Decimal);
                prmAmount.Value = Details.Amount;
                cmd.Parameters.Add(prmAmount);

                MySqlParameter prmVAT = new MySqlParameter("@VAT", MySqlDbType.Decimal);
                prmVAT.Value = Details.VAT;
                cmd.Parameters.Add(prmVAT);

                MySqlParameter prmVatableAmount = new MySqlParameter("@VatableAmount", MySqlDbType.Decimal);
                prmVatableAmount.Value = Details.VatableAmount;
                cmd.Parameters.Add(prmVatableAmount);

                MySqlParameter prmEVAT = new MySqlParameter("@EVAT", MySqlDbType.Decimal);
                prmEVAT.Value = Details.EVAT;
                cmd.Parameters.Add(prmEVAT);

                MySqlParameter prmEVatableAmount = new MySqlParameter("@EVatableAmount", MySqlDbType.Decimal);
                prmEVatableAmount.Value = Details.EVatableAmount;
                cmd.Parameters.Add(prmEVatableAmount);

                MySqlParameter prmLocalTax = new MySqlParameter("@LocalTax", MySqlDbType.Decimal);
                prmLocalTax.Value = Details.LocalTax;
                cmd.Parameters.Add(prmLocalTax);

                MySqlParameter prmisVATInclusive = new MySqlParameter("@isVATInclusive", MySqlDbType.Int16);
                prmisVATInclusive.Value = Convert.ToInt16(Details.isVATInclusive);
                cmd.Parameters.Add(prmisVATInclusive);

                MySqlParameter prmVariationMatrixID = new MySqlParameter("@VariationMatrixID", MySqlDbType.Int64);
                prmVariationMatrixID.Value = Details.VariationMatrixID;
                cmd.Parameters.Add(prmVariationMatrixID);

                MySqlParameter prmMatrixDescription = new MySqlParameter("@MatrixDescription", MySqlDbType.String);
                prmMatrixDescription.Value = Details.MatrixDescription;
                cmd.Parameters.Add(prmMatrixDescription);

                MySqlParameter prmProductGroup = new MySqlParameter("@ProductGroup", MySqlDbType.String);
                prmProductGroup.Value = Details.ProductGroup;
                cmd.Parameters.Add(prmProductGroup);

                cmd.Parameters.AddWithValue("@ProductSubGroup", Details.ProductSubGroup);
                cmd.Parameters.AddWithValue("@POItemStatus", Details.POItemStatus.ToString("d"));
                cmd.Parameters.AddWithValue("@IsVatable", Convert.ToInt16(Details.IsVatable));
                cmd.Parameters.AddWithValue("@Remarks", Details.Remarks);
                cmd.Parameters.AddWithValue("@SellingPrice", Details.SellingPrice);
                cmd.Parameters.AddWithValue("@SellingVAT", Details.SellingVAT);
                cmd.Parameters.AddWithValue("@SellingEVAT", Details.SellingEVAT);
                cmd.Parameters.AddWithValue("@SellingLocalTax", Details.SellingLocalTax);
                cmd.Parameters.AddWithValue("@OldSellingPrice", Details.OldSellingPrice);
                cmd.Parameters.AddWithValue("@RID", Details.RID);

                base.ExecuteNonQuery(cmd);

                SQL = "SELECT LAST_INSERT_ID();";

                cmd.Parameters.Clear();
                cmd.CommandText = SQL;

                string strDataTableName = "tbl" + this.GetType().FullName.Split(new Char[] { '.' })[this.GetType().FullName.Split(new Char[] { '.' }).Length - 1]; System.Data.DataTable dt = new System.Data.DataTable(strDataTableName);
                base.MySqlDataAdapterFill(cmd, dt);

                Int64 iID = 0;

                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    iID = Int64.Parse(dr[0].ToString());
                }

                PO clsPO = new PO(base.Connection, base.Transaction);
                clsPO.SynchronizeAmount(Details.POID);

                return(iID);
            }

            catch (Exception ex)
            {
                throw base.ThrowException(ex);
            }
        }
Beispiel #44
0
        //  // Change By Arpit to Create Parameters24th of August,2017
        //On the Basis of User defined % for each quantity of Product to verify
        public static void CreateParameters(List <int> _ProductList, List <int> _ProductQty, int M_MoveConfirm_ID, int VA010_QUalityPlan_ID, int CurrentQty, List <int> M_MoveConfirmLine_ID, Ctx ctx, Trx Trx_Name)
        {
            StringBuilder _sql = new StringBuilder();
            DataSet       _ds  = null;
            decimal       _qtyPercentToVerify = 0;
            decimal       _qtyFrom, _qtyTo, _qtyPercent = 0;

            try
            {
                _sql.Clear();
                _sql.Append(@"SELECT NVL(VA010_PercentQtyToVerify,0)VA010_PercentQtyToVerify,
                                NVL(VA010_ReceiptQtyFrom,0) VA010_ReceiptQtyFrom,
                                NVL(VA010_ReceiptQtyTo,0) VA010_ReceiptQtyTo FROM VA010_CheckingQty 
                              WHERE IsActive='Y' AND VA010_Qualityplan_ID=" + VA010_QUalityPlan_ID + " AND AD_Client_ID=" + ctx.GetAD_Client_ID());


                _ds = DB.ExecuteDataset(_sql.ToString(), null, Trx_Name);
                if (_ds != null && _ds.Tables[0].Rows.Count > 0)
                {
                    for (Int32 k = 0; k < _ds.Tables[0].Rows.Count; k++)
                    {
                        _qtyFrom    = Util.GetValueOfDecimal(_ds.Tables[0].Rows[k]["VA010_ReceiptQtyFrom"]);
                        _qtyTo      = Util.GetValueOfDecimal(_ds.Tables[0].Rows[k]["VA010_ReceiptQtyTo"]);
                        _qtyPercent = Util.GetValueOfDecimal(_ds.Tables[0].Rows[k]["VA010_PercentQtyToVerify"]);
                        if (CurrentQty >= _qtyFrom && _qtyTo == 0)
                        {
                            _qtyPercentToVerify = _qtyPercent;
                            k = _ds.Tables[0].Rows.Count;
                        }
                        else if (CurrentQty >= _qtyFrom && CurrentQty <= _qtyTo)
                        {
                            _qtyPercentToVerify = _qtyPercent;
                            k = _ds.Tables[0].Rows.Count;
                        }
                        else
                        {
                            _qtyPercentToVerify = 100;
                        }
                    }
                }
                else
                {
                    _qtyPercentToVerify = 100;
                }
                _sql.Clear();
                _sql.Append(@"SELECT VA010_QualityParameters_ID, VA010_TestPrmtrList_ID FROM va010_AssgndParameters WHERE"
                            + " VA010_QualityPlan_ID=" + VA010_QUalityPlan_ID + " AND IsActive='Y'");
                _ds.Clear();
                _ds = DB.ExecuteDataset(_sql.ToString(), null, Trx_Name);
                int _qty = 0;
                if (_ds != null)
                {
                    if (_ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < _ProductList.Count; i++)
                        {
                            _qty = 0;
                            _qty = (int)Math.Round((_ProductQty[i] * _qtyPercentToVerify) / 100, MidpointRounding.AwayFromZero);
                            if (_qty == 0)
                            {
                                _qty = _ProductQty[i];
                            }
                            if (_qty > _ProductQty[i])
                            {
                                _qty = _ProductQty[i];
                            }
                            for (int j = 0; j < _ds.Tables[0].Rows.Count; j++)
                            {
                                //Created Table object because not to use Mclass of Quality Control Module in our Base
                                MTable table = MTable.Get(ctx, "VA010_MoveConfParameters");
                                PO     pos   = table.GetPO(ctx, 0, Trx_Name);
                                pos.Set_ValueNoCheck("M_Product_ID", Util.GetValueOfInt(_ProductList[i]));
                                pos.Set_ValueNoCheck("VA010_QualityParameters_ID", Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA010_QualityParameters_ID"]));
                                pos.Set_ValueNoCheck("M_MovementLineConfirm_ID", Util.GetValueOfInt(M_MoveConfirmLine_ID[i]));
                                pos.Set_ValueNoCheck("VA010_TestPrmtrList_ID", Util.GetValueOfInt(_ds.Tables[0].Rows[j]["VA010_TestPrmtrList_ID"]));
                                pos.Set_ValueNoCheck("VA010_QuantityToVerify", Util.GetValueOfDecimal(_qty));
                                pos.Set_ValueNoCheck("AD_Client_ID", ctx.GetAD_Client_ID());
                                pos.Set_ValueNoCheck("AD_Org_ID", ctx.GetAD_Org_ID());

                                if (pos.Save(Trx_Name))
                                {
                                    ;
                                }
                                else
                                {
                                    Trx_Name.Rollback();
                                    Trx_Name.Close();
                                }
                            }
                            DB.ExecuteQuery(" UPDATE M_MovementLineConfirm SET VA010_QualCheckMark ='Y'  WHERE M_MovementLineConfirm_ID=" + M_MoveConfirmLine_ID[i], null, Trx_Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Log(Level.SEVERE, _sql.ToString(), ex);
            }
            finally
            {
                _sql.Clear();
                _ds.Dispose();
                _qtyPercentToVerify = _qtyFrom = _qtyTo = _qtyPercent = 0;
            }
        }
Beispiel #45
0
 public PO Add(PO po)
 {
     return(_poRepository.Add(po));
 }
 //internal static Worker Create(int id, PO.Worker worker)
 //{
 //    return Create(id, worker.Name);
 //}
 internal static Worker Create(PO.Worker worker)
 {
     return Create(worker.ID, worker.Name);
 }
Beispiel #47
0
 public void Update(PO po)
 {
     _poRepository.Update(po);
 }
Beispiel #48
0
        public bool UpdatePOReleaseQty(Session epiSession, string poNum, out string msgError)
        {
            msgError = "";
            bool result = false;

            if (epiSession.IsValidSession(epiSession.SessionID, epiSession.UserID))
            {
                try
                {
                    PO myPO = new PO(epiSession.ConnectionPool);

                    bool morePages = false;
                    PODataSet dsPO = new PODataSet();
                    dsPO = myPO.GetRows("PONum = " + poNum, "", "", "", "", "", "", "", "", 0, 1, out morePages);

                    DataRow drPO = dsPO.Tables["POHeader"].Select().Single();
                    string cal = drPO["ShortChar06"].ToString();

                    DataTable POLine = dsPO.Tables["PODetail"];
                    int i = 0;

                    foreach (DataRow list in dsPO.Tables["PORel"].Rows)
                    {
                        var item = POLine.Rows[i].ItemArray.ToArray();
                        decimal qty = 0;

                        if (cal == "1" || cal == "3" || cal == "4") { qty = Convert.ToDecimal(item[67].ToString()); }       //67=Number11, 
                        else if (cal == "2") { qty = Convert.ToDecimal(item[76].ToString()); }      //76=Number20

                        list.BeginEdit();
                        list["XRelQty"] = qty;
                        list["RelQty"] = qty;
                        list["BaseQty"] = qty;
                        list.EndEdit();
                        i++;
                    }

                    myPO.Update(dsPO);
                    result = true;
                    epiSession.Dispose();
                }
                catch (Exception ex)
                {
                    msgError = "Error : " + ex;                
                }
            }
            return result;
        }
 //	Set PO Workflow Manager
 //static
 //{
 //    PO.SetDocWorkflowMgr(Get());
 //}
 static DocWorkflowManager()
 {
     PO.SetDocWorkflowMgr(Get());
 }
 private void CurrentPO_DirtyChanged(PO.POFile file, bool newDirtyValue)
 {
     this.UpdateWindowTitle();
 }
        /// <summary>
        /// Process Document Value Workflow
        /// </summary>
        /// <param name="document">document</param>
        /// <param name="AD_Table_ID">table</param>
        /// <returns>true if WF started</returns>
        public bool Process(PO document, int AD_Table_ID)
        {
            _noCalled++;
            MWorkflow[] wfs = MWorkflow.GetDocValue(document.GetCtx(),
                                                    document.GetAD_Client_ID(), AD_Table_ID);
            if (wfs == null || wfs.Length == 0)
            {
                return(false);
            }

            bool started = false;

            for (int i = 0; i < wfs.Length; i++)
            {
                MWorkflow wf = wfs[i];
                //	We have a Document Workflow
                String logic = wf.GetDocValueLogic();
                if (logic == null || logic.Length == 0)
                {
                    log.Severe("Workflow has no Logic - " + wf.GetName());
                    continue;
                }

                //	Re-check: Document must be same Client as workflow
                if (wf.GetAD_Client_ID() != document.GetAD_Client_ID())
                {
                    continue;
                }

                //	Check Logic
                bool sql = logic.StartsWith("SQL=");
                if (sql && !TestStart(wf, document))
                {
                    log.Fine("SQL Logic evaluated to false (" + logic + ")");
                    continue;
                }
                if (!sql && !Evaluator.EvaluateLogic(document, logic))
                {
                    log.Fine("Logic evaluated to false (" + logic + ")");
                    continue;
                }

                if (document.Get_Trx() != null)
                {
                    ManageSkippedWF.Add(document.Get_Trx().SetUniqueTrxName(Trx.CreateTrxName("WFDV")), document);
                    log.Severe("Not started: " + wf);
                    continue;
                }
                //	Start Workflow
                log.Fine(logic);
                int         AD_Process_ID = 305;        //	HARDCODED
                ProcessInfo pi            = new ProcessInfo(wf.GetName(), AD_Process_ID, AD_Table_ID, document.Get_ID());
                pi.SetAD_User_ID(document.GetCtx().GetAD_User_ID());
                pi.SetAD_Client_ID(document.GetAD_Client_ID());
                //
                wf.GetCtx().SetContext("#AD_Client_ID", pi.GetAD_Client_ID().ToString());
                if (wf.Start(pi) != null)
                {
                    log.Config(wf.GetName());
                    _noStarted++;
                    started = true;
                }
            }
            return(started);
        }
Beispiel #52
0
        }       //	GetSourceColumn

        /**
         *  Is Criteria Met
         *	@param po po
         *	@return true if criteria is met
         */
        public bool IsMet(PO po)
        {
            MColumn column     = GetSourceColumn();
            String  columnName = column.GetColumnName();
            int     index      = po.Get_ColumnIndex(columnName);

            if (index == -1)
            {
                throw new Exception(ToString() + ": AD_Column_ID not found");
            }
            //	Get Value
            Object value = po.Get_Value(index);
            String op    = GetOperation();
            //	Compare Value
            String compareString = GetValueString();

            if (op.Equals(OPERATION_Sql))
            {
                compareString = GetSQLValue();
                op            = OPERATION_Eq;
            }
            //	NULL handling
            if (value == null)
            {
                if (compareString == null ||
                    compareString.Length == 0 ||
                    compareString.Equals("NULL", StringComparison.OrdinalIgnoreCase))
                {
                    if (op.Equals(OPERATION_Eq))
                    {
                        return(true);
                    }
                }
                else
                {
                    if (!op.Equals(OPERATION_Eq))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            if (GetRecord_ID() == 0 &&          //	no value to compare to
                (compareString == null || compareString.Length == 0))
            {
                return(false);
            }

            //	Like - String
            if (op.Equals(OPERATION_Like))
            {
                String s   = value.ToString();
                String cmp = compareString;
                if (cmp.IndexOf('%') != -1)             //	SQL Like
                {
                    log.Warning(ToString() + ": SQL LIKE not supported yet");
                    //TODO: SQL Like
                }
                return(s.ToUpper()
                       .IndexOf(cmp.ToUpper()) != 0);   //	substring
            }

            try
            {
                if (value is int)
                {
                    int ii  = (int)value;
                    int?cmp = null;
                    if (GetRecord_ID() > 0)
                    {
                        cmp = GetRecord_ID();
                    }
                    else
                    {
                        cmp = (int)int.Parse(compareString);
                    }
                    //	Tree Handling
                    bool?treeOp = (bool?)TreeOperation(columnName, cmp, op, ii, po.GetAD_Client_ID());
                    if (treeOp != null)
                    {
                        return(treeOp.Value);
                    }
                    //
                    if (op.Equals(OPERATION_Eq))
                    {
                        return(ii.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_NotEq))
                    {
                        return(!ii.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_Gt))
                    {
                        return(ii.CompareTo(cmp) > 0);
                    }
                    else if (op.Equals(OPERATION_GtEq))
                    {
                        return(ii.CompareTo(cmp) >= 0);
                    }
                    else if (op.Equals(OPERATION_Le))
                    {
                        return(ii.CompareTo(cmp) < 0);
                    }
                    else if (op.Equals(OPERATION_LeEq))
                    {
                        return(ii.CompareTo(cmp) <= 0);
                    }
                }
                else if (value is Decimal)
                {
                    Decimal bd  = (Decimal)value;
                    Decimal cmp = decimal.Parse(compareString);
                    if (op.Equals(OPERATION_Eq))
                    {
                        return(bd.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_NotEq))
                    {
                        return(!bd.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_Gt))
                    {
                        return(bd.CompareTo(cmp) > 0);
                    }
                    else if (op.Equals(OPERATION_GtEq))
                    {
                        return(bd.CompareTo(cmp) >= 0);
                    }
                    else if (op.Equals(OPERATION_Le))
                    {
                        return(bd.CompareTo(cmp) < 0);
                    }
                    else if (op.Equals(OPERATION_LeEq))
                    {
                        return(bd.CompareTo(cmp) <= 0);
                    }
                }
                else if (value is DateTime)
                {
                    DateTime?ts  = (DateTime?)value;
                    DateTime cmp = DateTime.Parse(compareString);
                    if (op.Equals(OPERATION_Eq))
                    {
                        return(ts.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_NotEq))
                    {
                        return(!ts.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_Gt))
                    {
                        return(ts.Value.CompareTo(cmp) > 0);
                    }
                    else if (op.Equals(OPERATION_GtEq))
                    {
                        return(ts.Value.CompareTo(cmp) >= 0);
                    }
                    else if (op.Equals(OPERATION_Le))
                    {
                        return(ts.Value.CompareTo(cmp) < 0);
                    }
                    else if (op.Equals(OPERATION_LeEq))
                    {
                        return(ts.Value.CompareTo(cmp) <= 0);
                    }
                }
                else
                // String
                {
                    String s   = value.ToString();
                    String cmp = compareString;
                    if (op.Equals(OPERATION_Eq))
                    {
                        return(s.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_NotEq))
                    {
                        return(!s.Equals(cmp));
                    }
                    else if (op.Equals(OPERATION_Gt))
                    {
                        return(s.CompareTo(cmp) > 0);
                    }
                    else if (op.Equals(OPERATION_GtEq))
                    {
                        return(s.CompareTo(cmp) >= 0);
                    }
                    else if (op.Equals(OPERATION_Le))
                    {
                        return(s.CompareTo(cmp) < 0);
                    }
                    else if (op.Equals(OPERATION_LeEq))
                    {
                        return(s.CompareTo(cmp) <= 0);
                    }
                }
            }
            catch (Exception e)
            {
                log.Warning(ToString() + ": " + e);
            }
            return(false);
        }       //	isMet
Beispiel #53
0
 internal void LineAdded(PO.Line line)
 {
     if (line == null)
         throw new ArgumentNullException("line");
     if (this._lines.Contains(line))
         throw new ArgumentException("The line is already in the file.", "line");
     int newSourceIndex = this._file.TextFile.Lines.IndexOf(line.Source);
     if (newSourceIndex < 0)
         throw new ArgumentException("The text line is not in the text file.", "line");
     int oldStartSourceIndex = this._file.TextFile.Lines.IndexOf(this._lines[0].Source);
     if (newSourceIndex < oldStartSourceIndex)
     {
         if (newSourceIndex == (oldStartSourceIndex - 1))
             this._lines.Insert(0, line);
         else
             throw new Exception("New line before the start of the entry block.");
     }
     else
     {
         int oldEndSourceIndex = this._file.TextFile.Lines.IndexOf(this._lines[this._lines.Count - 1].Source);
         if (newSourceIndex > oldEndSourceIndex)
         {
             if (newSourceIndex == (oldEndSourceIndex + 1))
                 this._lines.Add(line);
             else
                 throw new Exception("New line after the end of the entry block.");
         }
         else
             this._lines.Insert(newSourceIndex - oldStartSourceIndex, line);
     }
 }