/// <summary>
        /// Manually requests an order be created from <paramref name="from"/> to <paramref name="to"/> in the Requested state
        /// </summary>
        /// <param name="from">The <see cref="T:GIIS.DataLayer.HealthFacility"/> from which the order is originating (where stock originates)</param>
        /// <param name="to">The <see cref="T:GIIS.DataLayer.HealthFacility"/> to which the order is destined (where stock will end up)</param>
        /// <param name="orderDate">The date that the order is to take place</param>
        /// <returns>A constructed <see cref="T:GIIS.DataLayer.TransferOrderHeader"/> containing the constructed order items</returns>
        /// <remarks>
        /// Callers of this function will need to make subsequent calls to <see cref="M:GIIS.BusinessLogic.OrderManagementLogic.AddOrderLine(GIIS.DataLayer.TransferOrderHeader, System.String, System.String, System.Int32, GIIS.DataLayer.Uom) "/> function
        /// to add order lines.
        /// </remarks>
        public TransferOrderHeader RequestOrder(HealthFacility from, HealthFacility to, DateTime orderDate, Int32 modifiedBy)
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            else if (to == null)
            {
                throw new ArgumentNullException("to");
            }
            else if (orderDate == default(DateTime))
            {
                throw new ArgumentException("orderDate");
            }

            // Create the header
            TransferOrderHeader retVal = new TransferOrderHeader()
            {
                ModifiedBy              = modifiedBy,
                ModifiedOn              = DateTime.Now,
                OrderFacilityFrom       = from.Code,
                OrderFacilityTo         = to.Code,
                OrderSchedReplenishDate = orderDate,
                OrderStatus             = (int)OrderStatusType.Requested,
                RevNum = 0
            };

            // Save
            retVal.OrderNum = TransferOrderHeader.Insert(retVal);

            return(retVal);
        }
        /// <summary>
        /// Requests that an order be created based on the contents of the DRP table for the specified <paramref name="drpPlanId"/>
        /// </summary>
        /// <param name="facility">The health facility for which to create an order</param>
        /// <returns>The constructed <see cref="T:GIIS.DataLayer.TransferOrderHeader"/> instance which was constructed from the <paramref name="drpPlanId"/></returns>
        /// <remarks>
        /// <list type="ordered">
        /// <item><description>The function will create a new TransferOrderHeader DAL object</description></item>
        /// <item><description>	The function will load a HealthFacility object from the gln and gln_parent identifiers in the DRP table assigning them to the DAO object</description></item>
        /// <item><description>	The function will set the order status to “Requested”</description></item>
        /// <item><description>	The function will set the order date to the plan date</description></item>
        /// <item><description>	The function will save the order header.</description></item>
        /// <item><description>	For each item in the DRP plan the function will create a TransferOrderDetail objects using the AddOrderLine function in the Logic class using the specified quantity, gtin provided.       /// </remarks></description></item>
        /// </list>
        /// </remarks>
        public TransferOrderHeader RequestOrder(Int32[] drpIds, Int32 modifiedBy)
        {
            // HACK: Get this into the DAL
            StringBuilder drpIdsFilter = new StringBuilder();

            foreach (var id in drpIds)
            {
                drpIdsFilter.AppendFormat("{0},", id);
            }
            drpIdsFilter.Remove(drpIdsFilter.Length - 1, 1);

            string sql = String.Format("SELECT drp_plan.*, drp_facility.gln_parent FROM drp_plan INNER JOIN drp_facility USING (gln) WHERE drp_id IN ({0})", drpIdsFilter);

            using (var dt = DBManager.ExecuteReaderCommand(sql, System.Data.CommandType.Text, null))
            {
                // Create the order header
                TransferOrderHeader retVal = new TransferOrderHeader()
                {
                    ModifiedBy  = modifiedBy,
                    ModifiedOn  = DateTime.Now,
                    OrderStatus = (int)OrderStatusType.Requested
                };

                // Convert the datatable to a streamed reader
                using (var rdr = dt.CreateDataReader())
                {
                    while (rdr.Read())
                    {
                        retVal.OrderSchedReplenishDate = retVal.OrderSchedReplenishDate == default(DateTime) ? Convert.ToDateTime(rdr["plan_date"]) : retVal.OrderSchedReplenishDate;
                        retVal.OrderFacilityFrom       = retVal.OrderFacilityFrom ?? Convert.ToString(rdr["gln_parent"]);
                        retVal.OrderFacilityTo         = retVal.OrderFacilityTo ?? Convert.ToString(rdr["gln"]);

                        // Create line items
                        // Get the item/lot
                        var itemLot = this.GetOldestLot(retVal.OrderFacilityFromObject, Convert.ToString(rdr["gtin"]));
                        if (itemLot == null)
                        {
                            throw new InvalidOperationException("Cannot find item specified in gtin");
                        }

                        // Dtl
                        TransferOrderDetail dtl = new TransferOrderDetail()
                        {
                            OrderDetailDescription = itemLot.ItemObject.Name,
                            OrderNum          = retVal.OrderNum,
                            OrderGtin         = itemLot.Gtin,
                            OrderGtinLotnum   = itemLot.LotNumber,
                            OrderQty          = Convert.ToDouble(rdr["planned_order_receipt"]),
                            OrderQtyInBaseUom = Convert.ToDouble(rdr["planned_order_receipt"]),
                            OrderUom          = ItemManufacturer.GetItemManufacturerByGtin(itemLot.Gtin).BaseUom
                        };
                        dtl.OrderDetailNum = TransferOrderDetail.Insert(dtl);
                    }
                }

                retVal.OrderNum = TransferOrderHeader.Insert(retVal);

                return(retVal);
            }
        }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int userId = CurrentEnvironment.LoggedUser.Id;

                TransferOrderHeader o = new TransferOrderHeader();

                DateTime date = DateTime.ParseExact(txtOrderSchedReplenishDate.Text, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);
                o.OrderSchedReplenishDate = date;
                o.OrderFacilityFrom       = ddlHealthFacilityFrom.SelectedValue;
                o.OrderFacilityTo         = ddlHealthFacilityTo.SelectedValue;
                o.OrderStatus             = 0;//Requested
                o.OrderCarrier            = txtOrderCarrier.Text;
                o.ModifiedOn = DateTime.Now;
                o.ModifiedBy = userId;
                o.RevNum     = 0;

                int i = TransferOrderHeader.Insert(o);

                if (i > 0)
                {
                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                    //gridview_Databind(i);
                    // ClearControls(this);
                    HttpContext.Current.Session["_successTransferOrderHeader"] = "1";
                    HttpContext.Current.Session["_lastTransferOrderHeader"]    = i;

                    this.btnAdd.Visible        = false;
                    this.btnAddDetails.Visible = true;
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
        /// <summary>
        /// Request an order from a mini-drp run
        /// </summary>
        /// <param name="to">The facility which is the target of the drp run</param>
        /// <param name="modifiedBy">The user which is requesting the order from DRP run</param>
        public TransferOrderHeader RequestOrderFromDrp(HealthFacility to, Int32 modifiedBy)
        {
            // HACK: Currently this is running form SQL, should be run from DALs

            // TODO: Perform the mini-DRP run

            // Get the results of the run for the facility
            string sql = "GET_REPLENISHMENT_ORDER";

            using (var dt = DBManager.ExecuteReaderCommand(sql, System.Data.CommandType.StoredProcedure, new List <NpgsqlParameter>()
            {
                new NpgsqlParameter("HF_ID_IN", NpgsqlTypes.NpgsqlDbType.Varchar)
                {
                    Value = to.Code
                }
            }))
            {
                // Create the order header
                TransferOrderHeader retVal = new TransferOrderHeader()
                {
                    ModifiedBy              = modifiedBy,
                    ModifiedOn              = DateTime.Now,
                    OrderStatus             = (int)OrderStatusType.Requested,
                    OrderFacilityFrom       = to.Parent.Code,
                    OrderFacilityTo         = to.Code,
                    OrderSchedReplenishDate = DateTime.Now
                };

                List <TransferOrderDetail> dtls = new List <TransferOrderDetail>();

                // Convert the datatable to a streamed reader
                using (var rdr = dt.CreateDataReader())
                {
                    while (rdr.Read())
                    {
                        retVal.OrderSchedReplenishDate = retVal.OrderSchedReplenishDate == default(DateTime) ? Convert.ToDateTime(rdr["plan_date"]) : retVal.OrderSchedReplenishDate;

                        // Create line items
                        // Get the item/lot
                        var itemLot = this.GetOldestLot(retVal.OrderFacilityFromObject, Convert.ToString(rdr["gtin"]));
                        if (itemLot == null)
                        {
                            throw new InvalidOperationException("Cannot find item specified in gtin");
                        }

                        // Dtl
                        TransferOrderDetail dtl = new TransferOrderDetail()
                        {
                            OrderDetailDescription = Convert.ToString(rdr["name"]),
                            OrderNum          = retVal.OrderNum,
                            OrderGtin         = itemLot.Gtin,
                            OrderGtinLotnum   = itemLot.LotNumber,
                            OrderQty          = Convert.ToDouble(rdr["base_replenish_qty"]),
                            OrderQtyInBaseUom = Convert.ToDouble(rdr["base_replenish_qty"]),
                            OrderUom          = Convert.ToString(rdr["base_uom"])
                        };
                        dtls.Add(dtl);
                    }
                }

                retVal.OrderNum = TransferOrderHeader.Insert(retVal);
                foreach (var dtl in dtls)
                {
                    dtl.OrderNum = retVal.OrderNum;
                    TransferOrderDetail.Insert(dtl);
                }

                return(retVal);
            }
        }