/// <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);
            }
        }
    private void LoadReorderQuantity()
    {
        ItemManufacturer im = ItemManufacturer.GetItemManufacturerByGtin(ddlGtin.SelectedValue);

        if (im != null)
        {
            List <ReorderQuantity> list = new List <ReorderQuantity>();

            ReorderQuantity rqDose = new ReorderQuantity();
            rqDose.Quantity = 1;
            rqDose.Name     = "1 " + im.BaseUom;
            list.Add(rqDose);

            ReorderQuantity rqVial = new ReorderQuantity();
            rqVial.Quantity = im.Alt1QtyPer;
            rqVial.Name     = im.Alt1QtyPer + " " + im.BaseUom + " - 1 " + im.Alt1Uom;
            list.Add(rqVial);

            if (!string.IsNullOrEmpty(im.Alt2Uom))
            {
                ReorderQuantity rqBox = new ReorderQuantity();
                rqBox.Quantity = im.Alt2QtyPer;
                rqBox.Name     = im.Alt2QtyPer + " " + im.BaseUom + " - 1 " + im.Alt2Uom;
                list.Add(rqBox);
            }
            //txtReorderQty.Text = im.Alt2QtyPer.ToString();
            ddlReorderQty.DataSource     = list;
            ddlReorderQty.DataValueField = "Quantity";
            ddlReorderQty.DataTextField  = "Name";
            ddlReorderQty.DataBind();
        }
    }
        public bool CreateItem(List <int> manufacturersId, List <int> categoriesId, Item item)
        {
            var manufacturers = _itemContext.Manufacturers.Where(a => manufacturersId.Contains(a.Id)).ToList();
            var categories    = _itemContext.Categories.Where(c => categoriesId.Contains(c.Id)).ToList();



            foreach (var manufacturer in manufacturers)
            {
                var itemManufacturer = new ItemManufacturer()
                {
                    Manufacturer = manufacturer,
                    Item         = item
                };
                _itemContext.Add(itemManufacturer);
            }

            foreach (var category in categories)
            {
                var itemCategory = new ItemCategory()
                {
                    Category = category,
                    Item     = item
                };
                _itemContext.Add(itemCategory);
            }

            _itemContext.Add(item);

            return(Save());
        }
    protected void btnExcel_Click(object sender, EventArgs e)
    {
        //if (Session["ItemManufacturerList-ItemId"] != null)
        //{
        int itemId        = int.Parse(ddlItem.SelectedValue);
        int maximumRows   = int.MaxValue;
        int startRowIndex = 0;

        List <ItemManufacturer> list = ItemManufacturer.GetPagedItemManufacturerList(itemId, ref maximumRows, ref startRowIndex);

        gvExport.DataSource = list;
        gvExport.DataBind();
        gvExport.Visible = true;

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=ItemManufacturerList.xls");
        Response.Charset = "";

        // If you want the option to open the Excel file without saving then
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/ms-excel";
        System.IO.StringWriter       stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite   = new HtmlTextWriter(stringWrite);
        gvExport.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();

        gvExport.Visible = false;
        // }
    }
        public bool UpdateItem(List <int> categoriesId, List <int> manufacturersId, Item item)
        {
            var manufacturers = _itemContext.Manufacturers.Where(m => manufacturersId.Contains(m.Id)).ToList();
            var categories    = _itemContext.Categories.Where(c => categoriesId.Contains(c.Id)).ToList();

            var itemManufacturersToDelete = _itemContext.ItemManufacturers.Where(i => i.ItemId == item.Id);
            var itemCategoriesToDelete    = _itemContext.ItemCategories.Where(i => i.ItemId == item.Id);

            _itemContext.RemoveRange(itemManufacturersToDelete);
            _itemContext.RemoveRange(itemCategoriesToDelete);

            foreach (var manufacturer in manufacturers)
            {
                var itemManufacturer = new ItemManufacturer()
                {
                    Manufacturer = manufacturer,
                    Item         = item
                };
                _itemContext.Add(itemManufacturer);
            }

            foreach (var category in categories)
            {
                var itemCategory = new ItemCategory()
                {
                    Category = category,
                    Item     = item
                };
                _itemContext.Add(itemCategory);
            }

            _itemContext.Update(item);

            return(Save());
        }
    /// <summary>
    /// Set the selected items
    /// </summary>
    protected void ddlGTINParent_DataBound(object sender, EventArgs e)
    {
        string gtin = Request.QueryString["gtin"];

        if (!String.IsNullOrEmpty(gtin))
        {
            var o = ItemManufacturer.GetItemManufacturerByGtin(gtin);
            foreach (var itm in o.KitItems)
            {
                ddlGTINParent.Items.FindByValue(itm.Gtin).Selected = true;
            }
        }
        // HACK: Kit Items
    }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int i = 0;

                string gtin = Request.QueryString["gtin"];
                if (!String.IsNullOrEmpty(gtin))
                {
                    ItemManufacturer o = ItemManufacturer.GetItemManufacturerByGtin(gtin);
                    o.ModifiedBy = CurrentEnvironment.LoggedUser.Id;
                    o.ModifiedOn = DateTime.Now;

                    i = ItemManufacturer.Remove(gtin);
                    List <ItemManufacturer> imlist = o.KitItems;
                    foreach (ItemManufacturer im in imlist)
                    {
                        ItemManufacturer.Remove(im.Gtin);
                    }
                }

                if (i > 0)
                {
                    ClearControls(this);
                    gvItemManufacturer.Visible = true;
                    odsItemManufacturer.DataBind();
                    gvItemManufacturer.DataBind();

                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        try
        {
            int    id  = -1;
            string _id = Request.QueryString["id"].ToString();
            int.TryParse(_id, out id);
            int userId = CurrentEnvironment.LoggedUser.Id;

            int count = ItemManufacturer.GetCountManufacturer(id);
            if (count > 0)
            {
                lblWarningRemove.Visible = true;
                lblWarning.Visible       = false;
                lblSuccess.Visible       = false;
                lblError.Visible         = false;
            }
            else
            {
                int i = Manufacturer.Remove(id);

                if (i > 0)
                {
                    lblSuccess.Visible       = true;
                    lblWarning.Visible       = false;
                    lblError.Visible         = false;
                    lblWarningRemove.Visible = false;
                    gvManufacturer.DataBind();
                    ClearControls(this);
                }
                else
                {
                    lblSuccess.Visible       = false;
                    lblWarning.Visible       = true;
                    lblError.Visible         = false;
                    lblWarningRemove.Visible = false;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
        /// <summary>
        /// Gets the oldest lot in a facility of the specified <paramref name="gtin"/>
        /// </summary>
        /// <param name="facility">The facility in which the oldest lot should be found</param>
        /// <param name="gtin">The GTIN of the item to be found</param>
        /// <returns>The <see cref="T:GIIS.DataLayer.ItemLot"/> with the earliest expiry date</returns>
        public ItemLot GetOldestLot(HealthFacility facility, String gtin)
        {
            var oldestLot = from l in
                            (from v in HealthFacilityBalance.GetHealthFacilityBalanceByHealthFacilityCode(facility.Code)
                             where gtin == v.Gtin
                             select new { il = ItemLot.GetItemLotByGtinAndLotNo(gtin, v.LotNumber), hfb = v })
                            where l.il != null
                            orderby l.il.ExpireDate
                            select l;
            var candidateLot = (oldestLot.FirstOrDefault(o => o.hfb.Balance > 0) ?? oldestLot.FirstOrDefault());

            // Candidate lot is null when there is demand (from a kit item) with no lot available!
            if (candidateLot == null)
            {
                // Is it becaues there is no lot in existence?
                var itemLot = ItemLot.GetItemLotByGtin(gtin);
                if (itemLot == null)
                {
                    itemLot = new ItemLot()
                    {
                        Gtin      = gtin,
                        LotNumber = String.Format("N/A-{0}", gtin),
                        Notes     = "Automatically inserted by order system",
                        ItemId    = ItemManufacturer.GetItemManufacturerByGtin(gtin).ItemId
                    };
                    itemLot.Id = ItemLot.Insert(itemLot);
                }

                // Is there no balance?
                var balanceLot = HealthFacilityBalance.GetHealthFacilityBalanceByLotNumber(itemLot.LotNumber);
                if (balanceLot == null)
                {
                    HealthFacilityBalance.Insert(new HealthFacilityBalance()
                    {
                        Gtin = gtin,
                        HealthFacilityCode = facility.Code,
                        LotNumber          = itemLot.LotNumber
                    });
                }
                return(itemLot);
            }
            else
            {
                return(candidateLot.il);
            }
        }
    protected void cvGtin_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        string _gtin = "";

        if (!String.IsNullOrEmpty(txtGTIN.Text))
        {
            _gtin = txtGTIN.Text;
            if (ItemManufacturer.GetItemManufacturerByGtin(_gtin) != null)
            {
                args.IsValid = false;
            }
            string gtin = Request.QueryString["gtin"];
            if (!String.IsNullOrEmpty(gtin))
            {
                args.IsValid = true;
            }
        }
    }
    private int NewOrderDetail(string orderNumber, string gtin, double qty, string uom, string item)
    {
        TransferOrderDetail tod = new TransferOrderDetail();

        tod.OrderNum        = int.Parse(orderNumber);
        tod.OrderGtin       = gtin;
        tod.OrderGtinLotnum = "*";

        int quantity = 0;

        ItemManufacturer im = ItemManufacturer.GetItemManufacturerByGtin(gtin);

        if (uom.Equals(im.BaseUom))
        {
            quantity = (int)qty;
        }
        else if (uom.Equals(im.Alt1Uom))
        {
            quantity = (int)(qty * im.Alt1QtyPer);
        }
        else if (uom.Equals(im.Alt2Uom))
        {
            quantity = (int)(qty * im.Alt2QtyPer);
        }
        tod.OrderQty               = qty;
        tod.OrderQtyInBaseUom      = (double)quantity;
        tod.OrderUom               = uom;
        tod.ModifiedBy             = CurrentEnvironment.LoggedUser.Id;
        tod.ModifiedOn             = DateTime.Now;
        tod.OrderDetailDescription = item;
        tod.OrderDetailStatus      = 0; //requested

        int i = TransferOrderDetail.Insert(tod);

        return(i);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            List <string> actionList        = null;
            string        sessionNameAction = "";
            if (CurrentEnvironment.LoggedUser != null)
            {
                sessionNameAction = "__GIS_actionList_" + CurrentEnvironment.LoggedUser.Id;
                actionList        = (List <string>)Session[sessionNameAction];
            }

            if ((actionList != null) && actionList.Contains("ViewItemManufacturer") && (CurrentEnvironment.LoggedUser != null))
            {
                int    userId     = CurrentEnvironment.LoggedUser.Id;
                string language   = CurrentEnvironment.Language;
                int    languageId = int.Parse(language);
                Dictionary <string, string> wtList = (Dictionary <string, string>)HttpContext.Current.Cache["ItemManufacturer-dictionary" + language];
                if (wtList == null)
                {
                    List <WordTranslate> wordTranslateList = WordTranslate.GetWordByLanguage(languageId, "ItemManufacturer");
                    wtList = new Dictionary <string, string>();
                    foreach (WordTranslate vwt in wordTranslateList)
                    {
                        wtList.Add(vwt.Code, vwt.Name);
                    }
                    HttpContext.Current.Cache.Insert("ItemManufacturer-dictionary" + language, wtList);
                }

                //controls
                this.lblGTIN.Text         = wtList["ItemManufacturerGTIN"];
                this.lblItemCategory.Text = wtList["ItemManufacturerItemCategory"];
                this.lblManufacturer.Text = wtList["ItemManufacturerManufacturer"];
                this.lblItem.Text         = wtList["ItemManufacturerItem"];
                this.lblBaseUOM.Text      = wtList["ItemManufacturerBaseUOM"];
                this.lblPrice.Text        = wtList["ItemManufacturerPrice"];
                this.lblAlt1UOM.Text      = wtList["ItemManufacturerAlt1UOM"];
                this.lblAlt1Qty.Text      = wtList["ItemManufacturerAlt1Qty"];
                this.lblAlt2UOM.Text      = wtList["ItemManufacturerAlt2UOM"];
                this.lblAlt2Qty.Text      = wtList["ItemManufacturerAlt2Qty"];
                this.lblGTINParent.Text   = wtList["ItemManufacturerGTINParent"];
                //this.lblBaseUOMChild.Text = wtList["ItemManufacturerBaseUOMChild"];
                this.lblStorageSpace.Text = wtList["ItemManufacturerStorageSpace"];
                this.lblNotes.Text        = wtList["ItemManufacturerNotes"];
                this.lblIsActive.Text     = wtList["ItemManufacturerIsActive"];

                //grid header text
                gvItemManufacturer.Columns[0].HeaderText  = wtList["ItemManufacturerGTIN"];
                gvItemManufacturer.Columns[1].HeaderText  = wtList["ItemManufacturerItem"];
                gvItemManufacturer.Columns[2].HeaderText  = wtList["ItemManufacturerManufacturer"];
                gvItemManufacturer.Columns[3].HeaderText  = wtList["ItemManufacturerBaseUOM"];
                gvItemManufacturer.Columns[4].HeaderText  = wtList["ItemManufacturerAlt1UOM"];
                gvItemManufacturer.Columns[5].HeaderText  = wtList["ItemManufacturerAlt1Qty"];
                gvItemManufacturer.Columns[6].HeaderText  = wtList["ItemManufacturerAlt2UOM"];
                gvItemManufacturer.Columns[7].HeaderText  = wtList["ItemManufacturerAlt2Qty"];
                gvItemManufacturer.Columns[8].HeaderText  = wtList["ItemManufacturerGTINParent"];
                gvItemManufacturer.Columns[9].HeaderText  = wtList["ItemManufacturerIsActive"];
                gvItemManufacturer.Columns[10].HeaderText = wtList["ItemManufacturerNotes"];
                gvItemManufacturer.Columns[11].HeaderText = wtList["ItemManufacturerModifiedBy"];

                //actions
                this.btnEdit.Visible   = actionList.Contains("EditItemManufacturer");
                this.btnRemove.Visible = actionList.Contains("RemoveItemManufacturer");

                //buttons
                this.btnEdit.Text   = wtList["ItemManufacturerEditButton"];
                this.btnRemove.Text = wtList["ItemManufacturerRemoveButton"];

                //message
                this.lblSuccess.Text = wtList["ItemManufacturerSuccessText"];
                this.lblWarning.Text = wtList["ItemManufacturerWarningText"];
                this.lblError.Text   = wtList["ItemManufacturerErrorText"];

                //Page Title
                this.lblTitle.Text = wtList["ItemManufacturerTitle"];

                //selected object
                string gtin = Request.QueryString["gtin"];
                if (!String.IsNullOrEmpty(gtin))
                {
                    ItemManufacturer o = ItemManufacturer.GetItemManufacturerByGtin(gtin);

                    txtGTIN.Text = o.Gtin;
                    ddlItemCategory.DataBind();
                    ddlItemCategory.SelectedValue = o.ItemObject.ItemCategoryId.ToString();
                    odsItemCategory.DataBind();
                    odsItem.DataBind();
                    ddlItem.SelectedValue         = o.ItemId.ToString();
                    ddlManufacturer.SelectedValue = o.ManufacturerId.ToString();
                    ddlBaseUOM.SelectedValue      = o.BaseUom;
                    txtPrice.Text            = o.Price.ToString();
                    ddlAlt1UOM.SelectedValue = o.Alt1Uom;
                    txtAlt1Qty.Text          = o.Alt1QtyPer.ToString();
                    if (!string.IsNullOrEmpty(o.Alt2Uom))
                    {
                        ddlAlt2UOM.SelectedValue = o.Alt2Uom;
                        txtAlt2Qty.Text          = o.Alt2QtyPer.ToString();
                    }
                    rblIsActive.SelectedValue = o.IsActive.ToString();
                    txtStorageSpace.Text      = o.StorageSpace.ToString();
                    txtNotes.Text             = o.Notes;
                    gridview_Databind(gtin);
                }
                else
                {
                    btnRemove.Visible = false;
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
    }
Example #13
0
        /// <summary>
        /// Initialize the test data
        /// </summary>
        public static void InitializeTestDataset()
        {
            /// Transaction type 999 = ID
            var transactionTypes = TransactionType.GetTransactionTypeList();

            if (!transactionTypes.Exists(o => o.Name == "Allocation"))
            {
                TransactionType.Insert(new TransactionType()
                {
                    Name = "Allocation"
                });
            }
            if (!transactionTypes.Exists(o => o.Name == "Transfer"))
            {
                TransactionType.Insert(new TransactionType()
                {
                    Name = "Transfer"
                });
            }


            // GTIN 12345 - PHARMACO OPV
            if (ItemManufacturer.GetItemManufacturerByGtin(GTIN_UNDER_TEST) == null)
            {
                // Item Category 999 = Vaccine
                if (ItemCategory.GetItemCategoryById(VACCINE_CATEGORY_ID) == null)
                {
                    VACCINE_CATEGORY_ID = ItemCategory.Insert(new ItemCategory()
                    {
                        Id         = VACCINE_CATEGORY_ID,
                        Code       = "VACCINE",
                        IsActive   = true,
                        ModifiedBy = 1,
                        ModifiedOn = DateTime.Now,
                        Name       = "Vaccine"
                    });
                }

                // Item 999 - OPV
                if (Item.GetItemById(OPV_ITEM_ID) == null)
                {
                    OPV_ITEM_ID = Item.Insert(new Item()
                    {
                        Code           = "OPV",
                        EntryDate      = DateTime.Now,
                        Id             = OPV_ITEM_ID,
                        ItemCategoryId = VACCINE_CATEGORY_ID,
                        IsActive       = true,
                        ModifiedBy     = 1,
                        ModifiedOn     = DateTime.Now,
                        Name           = "OPV"
                    });
                }

                // Unit of Measure
                if (Uom.GetUomById(DOSE_UOM_ID) == null)
                {
                    DOSE_UOM_ID = Uom.Insert(new Uom()
                    {
                        Id   = DOSE_UOM_ID,
                        Name = "DOSE"
                    });
                }

                // Manufacturer 999 - PHARMACO
                if (Manufacturer.GetManufacturerById(PHARMACO_MANUFACTURER_ID) == null)
                {
                    PHARMACO_MANUFACTURER_ID = Manufacturer.Insert(new Manufacturer()
                    {
                        Id         = PHARMACO_MANUFACTURER_ID,
                        Code       = "PHX",
                        IsActive   = true,
                        ModifiedBy = 1,
                        ModifiedOn = DateTime.Now,
                        Name       = "PHARMACO INC."
                    });
                }

                ItemManufacturer.Insert(new ItemManufacturer()
                {
                    Alt1QtyPer = 20,
                    BaseUom    = "DOSE",
                    BaseUomChildPerBaseUomParent = 10,
                    Gtin           = GTIN_UNDER_TEST,
                    IsActive       = true,
                    ItemId         = OPV_ITEM_ID,
                    ManufacturerId = PHARMACO_MANUFACTURER_ID,
                    ModifiedBy     = 1,
                    ModifiedOn     = DateTime.Now,
                    Price          = 9.99,
                    StorageSpace   = 1,
                    Alt1Uom        = "DOSE",
                    Alt2QtyPer     = 30,
                    Alt2Uom        = "DOSE"
                });
            }

            if (ItemLot.GetItemLotByGtin(GTIN_UNDER_TEST) == null)
            {
                // Item 999 - OPV
                if (Item.GetItemById(OPV_ITEM_ID) == null)
                {
                    OPV_ITEM_ID = Item.Insert(new Item()
                    {
                        Code           = "OPV",
                        EntryDate      = DateTime.Now,
                        Id             = OPV_ITEM_ID,
                        ItemCategoryId = VACCINE_CATEGORY_ID,
                        IsActive       = true,
                        ModifiedBy     = 1,
                        ModifiedOn     = DateTime.Now,
                        Name           = "OPV"
                    });
                }

                ItemLot.Insert(new ItemLot()
                {
                    ExpireDate = DateTime.Now.AddDays(10),
                    Gtin       = GTIN_UNDER_TEST,
                    ItemId     = OPV_ITEM_ID,
                    LotNumber  = GTIN_LOT_USE_FIRST
                });

                // Item Lot 2 - Will be more stock and expires later
                ItemLot.Insert(new ItemLot()
                {
                    ExpireDate = DateTime.Now.AddDays(40),
                    Gtin       = GTIN_UNDER_TEST,
                    ItemId     = OPV_ITEM_ID,
                    LotNumber  = GTIN_LOT_USE_LAST
                });

                // Item Lot 3 - Will trigger low stock
                ItemLot.Insert(new ItemLot()
                {
                    ExpireDate = DateTime.Now.AddDays(80),
                    Gtin       = GTIN_UNDER_TEST,
                    ItemId     = OPV_ITEM_ID,
                    LotNumber  = GTIN_LOT_LOW_BAL
                });
            }

            // Type 3 = DISTRICT
            if (HealthFacilityType.GetHealthFacilityTypeById(6) == null)
            {
                HealthFacilityType.Insert(new HealthFacilityType()
                {
                    Id         = 3,
                    Code       = "DISTRICT",
                    IsActive   = true,
                    ModifiedBy = 1,
                    ModifiedOn = DateTime.Now,
                    Name       = "DISTRICT LEVEL"
                });
            }

            // Type 6 = SDP
            if (HealthFacilityType.GetHealthFacilityTypeById(6) == null)
            {
                HealthFacilityType.Insert(new HealthFacilityType()
                {
                    Id         = 6,
                    Code       = "SDP",
                    IsActive   = true,
                    ModifiedBy = 1,
                    ModifiedOn = DateTime.Now,
                    Name       = "SDP"
                });
            }

            // HF888 = DISTRICT
            if (HealthFacility.GetHealthFacilityByCode("HF888") == null)
            {
                HealthFacility.Insert(new HealthFacility()
                {
                    Id   = 888,
                    Code = "HF888",
                    ColdStorageCapacity = 1000,
                    IsActive            = true,
                    Leaf             = false,
                    ParentId         = HealthFacility.GetHealthFacilityByParentId(0)[0].Id,
                    TopLevel         = false,
                    TypeId           = 3,
                    VaccinationPoint = false,
                    VaccineStore     = true,
                    ModifiedBy       = 1,
                    ModifiedOn       = DateTime.Now
                });
            }

            // GIVE HEALTH FACILITY SOME BALANCE
            var hf888Balances = HealthFacilityBalance.GetHealthFacilityBalanceByHealthFacilityCode("HF888");
            HealthFacilityBalance useFirst = hf888Balances.Find(o => o.Gtin == GTIN_UNDER_TEST && o.LotNumber == GTIN_LOT_USE_FIRST),
                                  useLast  = hf888Balances.Find(o => o.Gtin == GTIN_UNDER_TEST && o.LotNumber == GTIN_LOT_USE_LAST),
                                  lowStock = hf888Balances.Find(o => o.Gtin == GTIN_UNDER_TEST && o.LotNumber == GTIN_LOT_LOW_BAL);

            if (useFirst == null)
            {
                useFirst = new HealthFacilityBalance()
                {
                    Allocated          = 0,
                    Balance            = 500,
                    Distributed        = 0,
                    Gtin               = GTIN_UNDER_TEST,
                    HealthFacilityCode = "HF888",
                    LotNumber          = GTIN_LOT_USE_FIRST,
                    Received           = 0,
                    StockCount         = 500,
                    Used               = 0,
                    Wasted             = 0
                };
                hf888Balances.Add(useFirst);
                HealthFacilityBalance.Insert(useFirst);
            }
            else
            {
                useFirst.Balance    = 500;
                useFirst.StockCount = 500;
                HealthFacilityBalance.Update(useFirst);
            }

            if (useLast == null)
            {
                useLast = new HealthFacilityBalance()
                {
                    Allocated          = 0,
                    Balance            = 1000,
                    Distributed        = 0,
                    Gtin               = GTIN_UNDER_TEST,
                    HealthFacilityCode = "HF888",
                    LotNumber          = GTIN_LOT_USE_LAST,
                    Received           = 0,
                    StockCount         = 1000,
                    Used               = 0,
                    Wasted             = 0
                };
                hf888Balances.Add(useLast);
                HealthFacilityBalance.Insert(useLast);
            }
            else
            {
                useLast.Balance    = 1000;
                useLast.StockCount = 1000;
                HealthFacilityBalance.Update(useLast);
            }

            if (lowStock == null)
            {
                lowStock = new HealthFacilityBalance()
                {
                    Allocated          = 0,
                    Balance            = 10,
                    Distributed        = 0,
                    Gtin               = GTIN_UNDER_TEST,
                    HealthFacilityCode = "HF888",
                    LotNumber          = GTIN_LOT_LOW_BAL,
                    Received           = 0,
                    StockCount         = 10,
                    Used               = 0,
                    Wasted             = 0
                };
                hf888Balances.Add(lowStock);
                HealthFacilityBalance.Insert(lowStock);
            }
            else
            {
                useLast.Balance    = 10;
                useLast.StockCount = 10;
                HealthFacilityBalance.Update(lowStock);
            }

            // HF999 = SDP
            if (HealthFacility.GetHealthFacilityByCode("HF999") == null)
            {
                HealthFacility.Insert(new HealthFacility()
                {
                    Id   = 999,
                    Code = "HF999",
                    ColdStorageCapacity = 100,
                    IsActive            = true,
                    Leaf             = true,
                    ParentId         = HealthFacility.GetHealthFacilityByCode("HF888").Id,
                    TopLevel         = false,
                    TypeId           = 6,
                    VaccinationPoint = true,
                    VaccineStore     = true,
                    ModifiedOn       = DateTime.Now,
                    ModifiedBy       = 1
                });
            }
        }
    protected void btnAddDetail_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                string orderNumber = "";
                if (Request.QueryString["orderNum"] != null)
                {
                    orderNumber = Request.QueryString["orderNum"].ToString();
                }
                TransferOrderHeader toh = TransferOrderHeader.GetTransferOrderHeaderByOrderNum(int.Parse(orderNumber));

                OrderManagementLogic oml = new OrderManagementLogic();
                string gtin = ddlGtin.SelectedValue;
                string lot  = "*";
                if (ddlItemLot.SelectedIndex > 0)
                {
                    lot = ddlItemLot.SelectedValue;
                }

                int qty      = 0;
                int quantity = 0;
                if (!String.IsNullOrEmpty(txtQuantity.Text))
                {
                    qty = int.Parse(txtQuantity.Text);
                    string uom = ddlUom.SelectedValue;

                    ItemManufacturer im = ItemManufacturer.GetItemManufacturerByGtin(gtin);
                    if (uom.Equals(im.BaseUom))
                    {
                        quantity = qty;
                    }
                    else if (uom.Equals(im.Alt1Uom))
                    {
                        quantity = qty * im.Alt1QtyPer;
                    }
                    else if (uom.Equals(im.Alt2Uom))
                    {
                        quantity = qty * im.Alt2QtyPer;
                    }
                }
                Uom u = Uom.GetUomByName(ddlUom.SelectedValue); //GetuomByName

                TransferOrderDetail tod = TransferOrderDetail.GetTransferOrderDetailByOrderNumGtinLotNumber(int.Parse(orderNumber), gtin, lot);
                if (tod == null)
                {
                    TransferOrderDetail td = oml.AddOrderLine(toh, gtin, lot, quantity, u, CurrentEnvironment.LoggedUser.Id);

                    if (td != null)
                    {
                        //ClearControls(this);
                        gvGtinValue.DataBind();
                        ddlGtin.SelectedIndex = 0;
                        //ddlItemLot.SelectedIndex = 0;
                        txtQuantity.Text   = string.Empty;
                        lblSuccess.Visible = true;
                        lblWarning.Visible = false;
                        lblError.Visible   = false;
                    }
                    else
                    {
                        lblSuccess.Visible = false;
                        lblWarning.Visible = false;
                        lblError.Visible   = true;
                    }
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = true;
                    lblError.Visible   = false;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
Example #15
0
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int userId = CurrentEnvironment.LoggedUser.Id;

                StockManagementLogic sml  = new StockManagementLogic();
                DateTime             date = DateTime.ParseExact(txtDate.Text, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);
                if (!String.IsNullOrEmpty(txtQuantity.Text))
                {
                    int qty = int.Parse(txtQuantity.Text);
                    AdjustmentReason adr = AdjustmentReason.GetAdjustmentReasonById(int.Parse(System.Configuration.ConfigurationManager.AppSettings["ReceiptAdjustmentReason"]));
                    HealthFacility   hf  = HealthFacility.GetHealthFacilityByCode(ddlHealthFacility.SelectedValue);

                    string           uom      = ddlUom.SelectedValue;
                    int              quantity = 0;
                    ItemManufacturer im       = ItemManufacturer.GetItemManufacturerByGtin(ddlGtin.SelectedValue);
                    if (uom.Equals(im.BaseUom))
                    {
                        quantity = qty;
                    }
                    else if (uom.Equals(im.Alt1Uom))
                    {
                        quantity = qty * im.Alt1QtyPer;
                    }
                    else if (uom.Equals(im.Alt2Uom))
                    {
                        quantity = qty * im.Alt2QtyPer;
                    }

                    //have base uom logic

                    string lot = string.Empty;
                    if (ddlItemLot.SelectedIndex != 0)
                    {
                        lot = ddlItemLot.SelectedValue;
                    }
                    ItemTransaction st = sml.Adjust(hf, ddlGtin.SelectedValue, lot, quantity, adr, CurrentEnvironment.LoggedUser.Id, date);
                    int             i  = st.Id;

                    if (i > 0)
                    {
                        ClearControls(this);

                        lblSuccess.Visible = true;
                        lblWarning.Visible = false;
                        lblError.Visible   = false;

                        odsTransactionLines.SelectParameters.Clear();
                        odsTransactionLines.SelectParameters.Add("i", i.ToString());
                        odsTransactionLines.DataBind();
                    }
                    else
                    {
                        lblSuccess.Visible = false;
                        lblWarning.Visible = false;
                        lblError.Visible   = true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int     i      = 0;
                Boolean insert = false;
                string  gtin   = Request.QueryString["gtin"];
                if (!String.IsNullOrEmpty(gtin))
                {
                    ItemManufacturer o = ItemManufacturer.GetItemManufacturerByGtin(gtin);
                    if (!String.IsNullOrEmpty(txtGTIN.Text))
                    {
                        o.Gtin = txtGTIN.Text;
                    }
                    o.ItemId         = int.Parse(ddlItem.SelectedValue.ToString());
                    o.ManufacturerId = int.Parse(ddlManufacturer.SelectedValue.ToString());
                    o.BaseUom        = ddlBaseUOM.SelectedValue.ToString();
                    if (!String.IsNullOrEmpty(txtPrice.Text))
                    {
                        o.Price = double.Parse(txtPrice.Text);
                    }
                    o.Alt1Uom = ddlAlt1UOM.SelectedValue.ToString();
                    if (!String.IsNullOrEmpty(txtAlt1Qty.Text))
                    {
                        o.Alt1QtyPer = int.Parse(txtAlt1Qty.Text);
                    }
                    o.Alt2Uom = ddlAlt2UOM.SelectedValue.ToString();
                    if (!String.IsNullOrEmpty(txtAlt2Qty.Text))
                    {
                        o.Alt2QtyPer = int.Parse(txtAlt2Qty.Text);
                    }
                    if (ddlGTINParent.GetSelectedIndices().Length > 0)
                    {
                        // Set kit items to the list
                        o.KitItems.Clear();
                        foreach (var idx in ddlGTINParent.GetSelectedIndices())
                        {
                            o.KitItems.Add(ItemManufacturer.GetItemManufacturerByGtin(ddlGTINParent.Items[idx].Value));
                        }
                    }
                    //if (!String.IsNullOrEmpty(txtBaseUOMChild.Text))
                    //    o.BaseUomChildPerBaseUomParent = double.Parse(txtBaseUOMChild.Text);
                    double storagespace = -1;
                    if (!String.IsNullOrEmpty(txtStorageSpace.Text))
                    {
                        double.TryParse(txtStorageSpace.Text, out storagespace);
                        o.StorageSpace = storagespace;
                    }
                    if (!String.IsNullOrEmpty(txtNotes.Text))
                    {
                        o.Notes = txtNotes.Text;
                    }

                    o.ModifiedBy = CurrentEnvironment.LoggedUser.Id;
                    o.ModifiedOn = DateTime.Now;
                    o.IsActive   = bool.Parse(rblIsActive.SelectedValue);

                    i = ItemManufacturer.Update(o);
                }
                else
                {
                    insert = true;
                    ItemManufacturer o = new ItemManufacturer();

                    if (!String.IsNullOrEmpty(txtGTIN.Text))
                    {
                        o.Gtin = txtGTIN.Text;
                    }
                    o.ItemId         = int.Parse(ddlItem.SelectedValue.ToString());
                    o.ManufacturerId = int.Parse(ddlManufacturer.SelectedValue.ToString());
                    o.BaseUom        = ddlBaseUOM.SelectedValue.ToString();
                    if (!String.IsNullOrEmpty(txtPrice.Text))
                    {
                        o.Price = double.Parse(txtPrice.Text);
                    }
                    if (ddlAlt1UOM.SelectedIndex != 0)
                    {
                        o.Alt1Uom = ddlAlt1UOM.SelectedValue.ToString();
                    }
                    if (!String.IsNullOrEmpty(txtAlt1Qty.Text))
                    {
                        o.Alt1QtyPer = int.Parse(txtAlt1Qty.Text);
                    }
                    if (ddlAlt2UOM.SelectedIndex != 0)
                    {
                        o.Alt2Uom = ddlAlt2UOM.SelectedValue.ToString();
                    }
                    if (!String.IsNullOrEmpty(txtAlt2Qty.Text))
                    {
                        o.Alt2QtyPer = int.Parse(txtAlt2Qty.Text);
                    }
                    if (ddlGTINParent.GetSelectedIndices().Length > 0)
                    {
                        // Set kit items to the list
                        o.KitItems.Clear();
                        foreach (var idx in ddlGTINParent.GetSelectedIndices())
                        {
                            o.KitItems.Add(ItemManufacturer.GetItemManufacturerByGtin(ddlGTINParent.Items[idx].Value));
                        }
                    }
                    //if (!String.IsNullOrEmpty(txtBaseUOMChild.Text))
                    //    o.BaseUomChildPerBaseUomParent = double.Parse(txtBaseUOMChild.Text);
                    double storagespace = -1;
                    if (!String.IsNullOrEmpty(txtStorageSpace.Text))
                    {
                        double.TryParse(txtStorageSpace.Text, out storagespace);
                        o.StorageSpace = storagespace;
                    }
                    if (!String.IsNullOrEmpty(txtNotes.Text))
                    {
                        o.Notes = txtNotes.Text;
                    }

                    o.IsActive   = true;
                    o.ModifiedOn = DateTime.Now;
                    o.ModifiedBy = CurrentEnvironment.LoggedUser.Id;

                    i    = ItemManufacturer.Insert(o);
                    gtin = o.Gtin;
                }

                if (i >= 0)
                {
                    if (insert)
                    {
                        List <HealthFacility> hfList = HealthFacility.GetHealthFacilityList();
                        foreach (HealthFacility hf in hfList)
                        {
                            GtinHfStockPolicy o = new GtinHfStockPolicy();
                            if (!String.IsNullOrEmpty(txtGTIN.Text))
                            {
                                o.Gtin = txtGTIN.Text;
                            }
                            o.HealthFacilityCode = hf.Code;

                            o.ReorderQty           = 1;
                            o.SafetyStock          = 0;
                            o.AvgDailyDemandRate   = 0;
                            o.LeadTime             = 1;
                            o.ConsumptionLogic     = "FEFO";
                            o.ForecastPeriodDemand = 0;

                            GtinHfStockPolicy.Insert(o);
                        }
                    }

                    ClearControls(this);
                    gvItemManufacturer.Visible = true;
                    gridview_Databind(gtin);

                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
    protected void gvGtinValue_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[0].Visible = false;

        TransferOrderHeader toh = null;
        string orderNumber      = Request.QueryString["OrderNum"];

        if (!string.IsNullOrEmpty(orderNumber))
        {
            toh = TransferOrderHeader.GetTransferOrderHeaderByOrderNum(int.Parse(orderNumber));
            if (toh.OrderStatus == 0)
            {
                e.Row.Cells[4].Visible = false;
            }
        }


        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label   lblOrderGtin = (Label)e.Row.FindControl("lblOrderGtin");
            TextBox txtValue     = (TextBox)e.Row.FindControl("txtValue");
            Label   lblId        = (Label)e.Row.FindControl("lblId");
            Label   lblId2       = (Label)e.Row.FindControl("lblId2");
            Label   lblItem      = (Label)e.Row.FindControl("lblItem");
            Label   lblFromStock = (Label)e.Row.FindControl("lblDistrictStock");

            DropDownList ddlUom = (DropDownList)e.Row.FindControl("ddlUom");
            DataTable    dt     = ItemManufacturer.GetUomFromGtin(lblOrderGtin.Text);
            // List<Uom> uomList = Uom.GetUomList();
            ddlUom.DataSource = dt;
            ddlUom.DataBind();


            //if (toh != null) // && toh.OrderStatus == 0)
            //    ddlUom.Enabled = true;
            //else ddlUom.Enabled = false;

            string id  = lblId.Text;
            int    id2 = int.Parse(lblId2.Text);

            TransferOrderDetail tod = TransferOrderDetail.GetTransferOrderDetailByOrderNumAndOrderDetail(int.Parse(id), id2);

            // lblFromStock.Text = GIIS.DataLayer.HealthFacilityBalance.GetHealthFacilityBalanceByHealthFacilityCode(toh.OrderFacilityFrom).Find(o=>o.Gtin == tod.OrderGtin).Balance.ToString();
            lblFromStock.Text += " " + tod.OrderUom;

            if (tod != null)
            {
                txtValue.Text        = tod.OrderQty.ToString();
                ddlUom.SelectedValue = tod.OrderUom;
                ddlUom.Enabled       = false;
            }


            DropDownList     ddlItemLot = (DropDownList)e.Row.FindControl("ddlItemLot");
            ObjectDataSource odsItemLot = (ObjectDataSource)e.Row.FindControl("odsItemLot");

            odsItemLot.SelectParameters.Clear();
            odsItemLot.SelectParameters.Add("gtin", lblOrderGtin.Text);
            odsItemLot.DataBind();
            ddlItemLot.DataSource = odsItemLot;
            ddlItemLot.DataBind();
            if (tod.OrderDetailStatus > 0)
            {
                ddlItemLot.SelectedValue = tod.OrderGtinLotnum;
            }
            if (tod.OrderDetailStatus == 3)
            {
                txtValue.Enabled   = false;
                ddlItemLot.Enabled = false;
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                string orderNumber = "";
                if (Request.QueryString["orderNum"] != null)
                {
                    orderNumber = Request.QueryString["orderNum"].ToString();
                }
                int index = 0;
                for (int rowIndex = 0; rowIndex < gvCreateTOD.Rows.Count; rowIndex++)
                {
                    //extract the TextBox values

                    Label        lblOrderGtin = (Label)gvCreateTOD.Rows[rowIndex].Cells[0].FindControl("lblGtin");
                    TextBox      txtValue     = (TextBox)gvCreateTOD.Rows[rowIndex].Cells[2].FindControl("txtQty");
                    Label        lblItem      = (Label)gvCreateTOD.Rows[rowIndex].Cells[1].FindControl("lblGtinItem");
                    DropDownList ddlUom       = (DropDownList)gvCreateTOD.Rows[rowIndex].Cells[3].FindControl("ddlUom2");

                    if (!String.IsNullOrEmpty(txtValue.Text))
                    {
                        string gtin = lblOrderGtin.Text;
                        string uom  = ddlUom.SelectedValue;
                        double qty  = double.Parse(txtValue.Text);
                        string item = lblItem.Text;

                        index = NewOrderDetail(orderNumber, gtin, qty, uom, item);

                        if (index > 0)
                        {
                            List <ItemManufacturer> imlist = ItemManufacturer.GetItemManufacturerByParentGtin(gtin);
                            if (imlist.Count > 0)
                            {
                                foreach (ItemManufacturer imo in imlist)
                                {
                                    index = NewOrderDetail(orderNumber, imo.Gtin, qty, uom, imo.ItemObject.Code);
                                }
                            }
                        }
                    }
                }
                if (index > 0)
                {
                    lblSuccess.Visible  = true;
                    lblWarning.Visible  = false;
                    lblError.Visible    = false;
                    gvCreateTOD.Visible = false;
                    gvGtinValue.Visible = true;
                    odsGtinValue.SelectParameters.Clear();
                    odsGtinValue.SelectParameters.Add("orderNumber", orderNumber);
                    odsGtinValue.SelectParameters.Add("healthFacilityCode", CurrentEnvironment.LoggedUser.HealthFacility.Code);
                    gvGtinValue.DataSourceID = "odsGtinValue";
                    gvGtinValue.DataBind();
                    tbl.Visible          = true;
                    ddlGtin.Visible      = true;
                    ddlUom.Visible       = true;
                    txtQuantity.Visible  = true;
                    btnAdd.Visible       = false;
                    btnEdit.Visible      = true;
                    btnAddDetail.Visible = true;
                    btnRelease.Visible   = true;
                    btnCancel.Visible    = true;

                    ////bind ddl
                    //List<Uom> uomList = Uom.GetUomList();
                    //ddlUom.DataSource = uomList;
                    //ddlUom.DataBind();

                    DataTable dt = HealthFacilityBalance.GetItemManufacturerBalanceForDropDown(CurrentEnvironment.LoggedUser.HealthFacilityId);
                    ddlGtin.DataSource = dt;
                    ddlGtin.DataBind();
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
        /// <summary>
        /// Performs stock transaction for a vaccination event
        /// </summary>
        /// <param name="facility">The facility in which the vaccination event occurred</param>
        /// <param name="vaccination">The vaccination event</param>
        /// <returns>The <see cref="T:GIIS.DataLayer.ItemTransaction"/> representing the transfer</returns>
        public ItemTransaction Vaccinate(HealthFacility facility, VaccinationEvent vaccination)
        {
            // Vaccination not given = no transaction
            if (!vaccination.VaccinationStatus)
            {
                return(null);
            }

            List <ItemLot> lots = new List <ItemLot>();

            // Verify
            if (facility == null)
            {
                throw new ArgumentNullException("facility");
            }
            else if (vaccination == null)
            {
                throw new ArgumentNullException("vaccination");
            }
            else if (String.IsNullOrEmpty(vaccination.VaccineLot))
            {
                ItemManufacturer     gtin = ItemManufacturer.GetItemManufacturerByItem(vaccination.Dose.ScheduledVaccination.ItemId);
                OrderManagementLogic oml  = new OrderManagementLogic();
                lots.Add(oml.GetOldestLot(facility, gtin.Gtin));
            }

            //throw new ArgumentException("Vaccination event missing lot#", "vaccination");

            // Item lot that was used
            if (lots.Count == 0)
            {
                lots.Add(ItemLot.GetItemLotById(vaccination.VaccineLotId));
            }
            //lots.Add(ItemLot.GetItemLotByLotNumber(vaccination.VaccineLot));
            if (lots.Count == 0)
            {
                return(null);
            }


            // throw new InvalidOperationException("Cannot find the specified ItemLot relation (GTIN)");

            // Transaction type
            TransactionType vaccinationType = TransactionType.GetTransactionTypeList().FirstOrDefault(o => o.Name == "Vaccination");

            if (vaccinationType == null)
            {
                throw new InvalidOperationException("Cannot find transaction type 'Vaccination'");
            }

            // Return value
            ItemTransaction retVal = null;

            // Iterate through lots
            for (int i = 0; i < lots.Count; i++)
            {
                var lot = lots[i];

                // Get balance
                HealthFacilityBalance balance = this.GetCurrentBalance(facility, lot.Gtin, lot.LotNumber);
                //if (balance.Balance < 1)
                //    throw new InvalidOperationException("Insufficient doses to register vaccination event");

                // Create a transaction
#if XAMARIN
#else
#endif
                ItemTransaction itl = new ItemTransaction()
                {
                    Gtin                    = lot.Gtin,
                    GtinLot                 = lot.LotNumber,
                    HealthFacilityCode      = facility.Code,
                    ModifiedBy              = vaccination.ModifiedBy,
                    ModifiedOn              = vaccination.ModifiedOn,
                    RefIdNum                = vaccination.Id,
                    TransactionDate         = vaccination.VaccinationDate,
                    TransactionQtyInBaseUom = -1,
                    TransactionTypeId       = vaccinationType.Id
                };
                if (String.IsNullOrEmpty(vaccination.VaccineLot))
                {
                    vaccination.VaccineLotId = lot.Id;
                    VaccinationEvent.Update(vaccination);
                }

                // Update facility balances
                balance.Balance -= 1;
                balance.Used    += 1;

                // Now save
                HealthFacilityBalance.Update(balance);
                itl.Id = ItemTransaction.Insert(itl);

                if (retVal == null)
                {
                    retVal = itl;
                }

                // Linked or kitted items
                var lotGtinItem = ItemManufacturer.GetItemManufacturerByGtin(lot.Gtin);
                foreach (var im in lotGtinItem.KitItems)
                {
                    lots.Add(new OrderManagementLogic().GetOldestLot(facility, im.Gtin));
                }
            }

            return(retVal);
        }
Example #20
0
        /// <summary>
        /// Map a facility
        /// </summary>
        static OpenIZ.Core.Model.Entities.ManufacturedMaterial MapMaterial(ItemLot item, DatasetInstall context)
        {
            Guid id = Guid.NewGuid();

            manufacturedMaterialMap.Add(item.Id, id);
            EntitySource.Current = new EntitySource(new DummyEntitySource());

            Guid materialId = Guid.Empty;

            if (!materialMap.TryGetValue(item.ItemId, out materialId))
            {
                materialId = Guid.NewGuid();
                Material material = new Material()
                {
                    Key                  = materialId,
                    ExpiryDate           = item.ItemObject.ExitDate,
                    FormConceptKey       = Guid.Parse(item.ItemObject.Name == "OPV" ? "66CBCE3A-2E77-401D-95D8-EE0361F4F076" : "9902267C-8F77-4233-BFD3-E6B068AB326A"),
                    DeterminerConceptKey = DeterminerKeys.Described,
                    Identifiers          = new List <EntityIdentifier>()
                    {
                        new EntityIdentifier(new AssigningAuthority("TIIS_ITEM", "TIIS Item Identifiers", "1.3.6.1.4.1.33349.3.1.5.102.3.5.12"), item.ItemId.ToString())
                    },
                    Names = new List <EntityName>()
                    {
                        new EntityName(NameUseKeys.OfficialRecord, item.ItemObject.Name)
                    },
                    StatusConceptKey = item.ItemObject.IsActive ? StatusKeys.Active : StatusKeys.Obsolete
                };
                context.Action.Add(new DataUpdate()
                {
                    InsertIfNotExists = true, Element = material
                });
                materialMap.Add(item.ItemId, materialId);
            }

            // Organization map?
            Guid organizationId = Guid.Empty;
            var  gtinObject     = ItemManufacturer.GetItemManufacturerByGtin(item.Gtin);

            if (gtinObject != null && !manufacturerMap.TryGetValue(gtinObject.ManufacturerId, out organizationId))
            {
                organizationId = Guid.NewGuid();
                Organization organization = new Organization()
                {
                    Key         = organizationId,
                    Identifiers = new List <EntityIdentifier>()
                    {
                        new EntityIdentifier(new AssigningAuthority("MANUFACTURER_CODE", "Manufacturer Codes", "1.3.6.1.4.1.33349.3.1.5.102.3.5.14"), gtinObject.ManufacturerObject.Code),
                        new EntityIdentifier(new AssigningAuthority("TIIS_MANUFACTURER", "TIIS Manufacturer Identifiers", "1.3.6.1.4.1.33349.3.1.5.102.3.5.13"), gtinObject.ManufacturerId.ToString())
                    },
                    Names = new List <EntityName>()
                    {
                        new EntityName(NameUseKeys.OfficialRecord, gtinObject.ManufacturerObject.Name)
                    },
                    StatusConceptKey   = gtinObject.ManufacturerObject.IsActive ? StatusKeys.Active : StatusKeys.Obsolete,
                    IndustryConceptKey = industryManufacturer
                };
                context.Action.Add(new DataUpdate()
                {
                    InsertIfNotExists = true, Element = organization
                });
                manufacturerMap.Add(gtinObject.ManufacturerId, organizationId);
            }

            Guid typeConceptKey = Guid.Empty;

            materialTypeMap.TryGetValue(item.ItemId, out typeConceptKey);

            // TODO: Migrate over kit items
            // TODO: Link boxes/vials/doses
            // Core construction of place
            ManufacturedMaterial retVal = new ManufacturedMaterial()
            {
                Key            = id,
                TypeConceptKey = typeConceptKey == Guid.Empty ? (Guid?)null : typeConceptKey,
                Relationships  = new List <EntityRelationship>()
                {
                    new EntityRelationship(EntityRelationshipTypeKeys.ManufacturedProduct, id)
                    {
                        SourceEntityKey = materialId
                    },
                },
                Names = new List <EntityName>()
                {
                    new EntityName(NameUseKeys.Assigned, String.Format("{0} ({1})", item.ItemObject.Name, gtinObject?.ManufacturerObject.Name))
                },
                ExpiryDate  = item.ExpireDate,
                LotNumber   = item.LotNumber,
                Identifiers = new List <EntityIdentifier>()
                {
                    new EntityIdentifier(new AssigningAuthority("GTIN", "GS1 Global Trade Identification Number (GTIN)", "1.3.160"), item.Gtin),
                    new EntityIdentifier(new AssigningAuthority("GIIS_ITEM_ID", "GIIS Item Identifiers", "1.3.6.1.4.1.33349.3.1.5.102.3.5.15"), item.Id.ToString())
                },
                IsAdministrative = false,
                StatusConceptKey = StatusKeys.Active
            };

            if (organizationId != Guid.Empty)
            {
                retVal.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.WarrantedProduct, id)
                {
                    SourceEntityKey = organizationId
                });
            }

            return(retVal);
        }