protected void btnExcel_Click(object sender, EventArgs e)
    {
        int    itemId        = int.Parse(ddlItem.SelectedValue);
        string gtin          = ddlGtin.SelectedValue;
        int    maximumRows   = int.MaxValue;
        int    startRowIndex = 0;

        List <ItemLot> list = ItemLot.GetPagedItemLotList(itemId, gtin, 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;
    }
Exemplo n.º 2
0
        public ItemLotPopulator(List <Merchandise> merchandises)
        {
            itemLots = new List <ItemLot>();

            foreach (Merchandise merchadise in merchandises)
            {
                ItemLot lot = GenerateRandomLot(merchadise);
                itemLots.Add(lot);
            }
        }
Exemplo n.º 3
0
    protected void gvItemLot_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string dateformat = ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat;

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label   lblEntryDate  = (Label)e.Row.FindControl("lblEntryDate");
            Label   lblExpireDate = (Label)e.Row.FindControl("lblExpireDate");
            ItemLot lot           = ItemLot.GetItemLotById(int.Parse(e.Row.Cells[10].Text));
            //lblEntryDate.Text = lot.EntryDate.ToString(dateformat);
            lblExpireDate.Text = lot.ExpireDate.ToString(dateformat);
        }
    }
 /// <summary>
 /// Performs rollback of stock transaction for a vaccination event
 /// </summary>
 /// <param name="facility">The healthfacility where the vaccination event happened</param>
 /// <param name="vaccineLotId">The vaccine lot that was used in the vaccination event</param>
 public int ClearBalance(HealthFacility facility, int vaccineLotId)
 {
     if (vaccineLotId > 0)
     {
         ItemLot il = ItemLot.GetItemLotById(vaccineLotId);
         HealthFacilityBalance hb = HealthFacilityBalance.GetHealthFacilityBalance(facility.Code, il.Gtin, il.LotNumber);
         if (hb != null)
         {
             hb.Used    -= 1;
             hb.Balance += 1;
             int i = HealthFacilityBalance.Update(hb);
             return(i);
         }
     }
     return(-1);
 }
Exemplo n.º 5
0
        //This needs to be able to swap individual drops and their chance of dropping around instead of the whole drop table to an enemy
        private void RandomiseEnemyLots()
        {
            List <ItemLot> cachedEnemyLots = MainWindow.GameWorld.GetAllEnemyItemLots();

            foreach (var item in cachedEnemyLots)
            {
                ItemLot itemToSwapWith = cachedEnemyLots[rng.Next(cachedEnemyLots.Count)];

                while (itemToSwapWith.ID == item.ID)
                {
                    itemToSwapWith = cachedEnemyLots[rng.Next(cachedEnemyLots.Count)];
                }

                item.SwapItemLotValues(itemToSwapWith);
            }
        }
Exemplo n.º 6
0
        private void RandomiseBossSouls()
        {
            List <ItemLot> cachedBossSouls    = MainWindow.GameWorld.GetAllBossSouls();
            List <ItemLot> cachedTreasureLots = MainWindow.GameWorld.GetAllTreasureLots();

            foreach (var item in cachedBossSouls)
            {
                ItemLot itemToSwapWith = cachedTreasureLots[rng.Next(cachedTreasureLots.Count)];
                while (itemToSwapWith.ID == item.ID || (int)itemToSwapWith.ItemLotItems.First().ItemCategory == -1 || IDBanks.forbiddenItemLotIds.Contains(itemToSwapWith.ID))
                {
                    itemToSwapWith = cachedTreasureLots[rng.Next(cachedTreasureLots.Count)];
                }

                item.SwapItemLotValues(itemToSwapWith);
            }
        }
        /// <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);
            }
        }
Exemplo n.º 8
0
        private void RandomiseTreasureLots()
        {
            List <ItemLot> cachedTreasureLots = MainWindow.GameWorld.GetAllTreasureLots();

            foreach (var item in cachedTreasureLots)
            {
                if ((int)item.ItemLotItems[0].LotItemCategory != -1)
                {
                    ItemLot itemToSwapWith = cachedTreasureLots[rng.Next(cachedTreasureLots.Count)];
                    while (itemToSwapWith.ID == item.ID || (int)itemToSwapWith.ItemLotItems[0].LotItemCategory == -1)
                    {
                        itemToSwapWith = cachedTreasureLots[rng.Next(cachedTreasureLots.Count)];
                    }

                    item.SwapItemLotValues(itemToSwapWith);
                }
            }
        }
Exemplo n.º 9
0
        private void RandomiseShopItems()
        {
            List <ShopLot> cachedShopItems    = MainWindow.GameWorld.GetAllShopItems();
            List <ItemLot> cachedTreasureLots = MainWindow.GameWorld.GetAllTreasureLots();

            foreach (var shopLot in cachedShopItems)
            {
                //We do not want to potentially reinsert key items that have been swapped into the shop back into the world at forbidden id's
                if (!IDBanks.keyItems.Contains(shopLot.ShopLotItem.EquipID))
                {
                    //Decide if swapping with vendor or with world items
                    bool swapWithWorldItem = true;

                    //swapWithWorldItem = rng.Next(0, 2) > 0;

                    if (swapWithWorldItem)
                    {
                        //Pick a random treasure to swap with, make sure its not a NORMAL soul drop
                        ItemLot treasureItemToSwapWith = cachedTreasureLots[rng.Next(cachedTreasureLots.Count)];
                        while (shopLot.ownerShopKeeper.HasShopLotItem(treasureItemToSwapWith) || Convert.ToInt64(treasureItemToSwapWith.ItemLotItems[0].ItemCategory) == -1 || IDBanks.soulsIds.Contains(treasureItemToSwapWith.ItemLotItems[0].ID))
                        {
                            treasureItemToSwapWith = cachedTreasureLots[rng.Next(cachedTreasureLots.Count)];
                        }

                        shopLot.SwapItemLotValues(treasureItemToSwapWith.ItemLotItems[0]);
                    }

                    if (!swapWithWorldItem)
                    {
                        //Don't swap an item with itself
                        ShopLot shopItemToSwapWith = cachedShopItems[rng.Next(cachedShopItems.Count)];
                        while (shopItemToSwapWith.ID == shopLot.ID || shopLot.ownerShopKeeper.HasShopLotItem(shopItemToSwapWith.ShopLotItem))
                        {
                            shopItemToSwapWith = cachedShopItems[rng.Next(cachedShopItems.Count)];
                        }

                        shopLot.SwapItemLotValues(shopItemToSwapWith.ShopLotItem);
                    }
                }
            }
        }
Exemplo n.º 10
0
    protected void cvGtinLotNumber_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        string _gtin  = "";
        string _lotno = "";
        string gtin   = Request.QueryString["gtin"];
        string lotno  = Request.QueryString["lotno"];

        if (String.IsNullOrEmpty(gtin) && String.IsNullOrEmpty(lotno))
        {
            if (!String.IsNullOrEmpty(ddlGtin.SelectedValue) && !String.IsNullOrEmpty(txtLotNumber.Text))
            {
                _gtin  = ddlGtin.SelectedValue;
                _lotno = txtLotNumber.Text;
                if (ItemLot.GetItemLotByGtinAndLotNo(_gtin, _lotno) != null)
                {
                    args.IsValid = false;
                }
                lblSuccess.Visible = false;
            }
        }
    }
    protected void gvHealthFacilityBalance_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string dateformat = ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat;

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label   lblExpireDate = (Label)e.Row.FindControl("lblExpireDate");
            ItemLot lot           = ItemLot.GetItemLotByGtinAndLotNo(e.Row.Cells[1].Text, e.Row.Cells[3].Text);
            if (lot != null)
            {
                lblExpireDate.Text = lot.ExpireDate.ToString("dd-MMM-yyyy");
            }
            int days = int.Parse(Configuration.GetConfigurationByName("LimitNumberOfDaysBeforeExpire").Value);
            if (lot.ExpireDate < DateTime.Today.Date)
            {
                e.Row.Cells[4].BackColor = System.Drawing.Color.OrangeRed;
            }
            else if (lot.ExpireDate < DateTime.Today.Date.AddDays(days))
            {
                e.Row.Cells[4].BackColor = System.Drawing.Color.Yellow;
            }
        }
    }
Exemplo n.º 12
0
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        try
        {
            int    id     = -1;
            int    userId = CurrentEnvironment.LoggedUser.Id;
            string gtin   = Request.QueryString["gtin"];
            string lotno  = Request.QueryString["lotno"];

            if (!String.IsNullOrEmpty(gtin) && !String.IsNullOrEmpty(lotno))
            {
                ItemLot o = ItemLot.GetItemLotByGtinAndLotNo(gtin, lotno);

                int i = ItemLot.Remove(o.Id);
                if (i > 0)
                {
                    lblSuccess.Visible = true;
                    lblWarning.Visible = false;
                    lblError.Visible   = false;
                    ClearControls(this);
                    gvItemLotNew.Visible = false;
                }
                else
                {
                    lblSuccess.Visible = false;
                    lblWarning.Visible = false;
                    lblError.Visible   = true;
                }
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Visible = false;
            lblWarning.Visible = false;
            lblError.Visible   = true;
        }
    }
Exemplo n.º 13
0
    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("ViewItemLot") && (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["ItemLot-dictionary" + language];
                if (wtList == null)
                {
                    List <WordTranslate> wordTranslateList = WordTranslate.GetWordByLanguage(languageId, "ItemLot");
                    wtList = new Dictionary <string, string>();
                    foreach (WordTranslate vwt in wordTranslateList)
                    {
                        wtList.Add(vwt.Code, vwt.Name);
                    }
                    HttpContext.Current.Cache.Insert("ItemLot-dictionary" + language, wtList);
                }

                //controls
                lblItemCategory.Text = wtList["ItemLotItemCategory"];
                lblItem.Text         = wtList["ItemLotItem"];
                lblGTIN.Text         = wtList["ItemLotGTIN"];
                lblLotNumber.Text    = wtList["ItemLotLotNumber"];
                lblExpireDate.Text   = wtList["ItemLotExpireDate"];
                lblNotes.Text        = wtList["ItemLotNotes"];

                //grid header text
                gvItemLotNew.Columns[0].HeaderText = wtList["ItemLotGTIN"];
                gvItemLotNew.Columns[1].HeaderText = wtList["ItemLotLotNumber"];
                gvItemLotNew.Columns[2].HeaderText = wtList["ItemLotItem"];
                gvItemLotNew.Columns[3].HeaderText = wtList["ItemLotExpireDate"];
                gvItemLotNew.Columns[4].HeaderText = wtList["ItemLotNotes"];

                //validators
                string format    = ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat;
                string expresion = ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateExpresion;
                ceExpireDate.Format                = format;
                revExpireDate.ErrorMessage         = format;
                revExpireDate.ValidationExpression = expresion;

                //actions
                btnEdit.Visible = actionList.Contains("EditItemLot");
                //btnRemove.Visible = actionList.Contains("RemoveItemLot");

                //buttons
                btnEdit.Text = wtList["ItemLotEditButton"];
                //btnRemove.Text = wtList["ItemLotRemoveButton"];

                ////message
                lblSuccess.Text              = wtList["ItemLotSuccessText"];
                lblWarning.Text              = wtList["ItemLotWarningText"];
                lblError.Text                = wtList["ItemLotErrorText"];
                cvItemLotNew.ErrorMessage    = wtList["ItemLotMandatory"];
                cvDate.ErrorMessage          = wtList["ItemLotDateValidator"];
                cvGtinLotNumber.ErrorMessage = wtList["ItemLotDuplicateCheck"];

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

                //selected object
                string _gtin  = Request.QueryString["gtin"];
                string _lotNo = Request.QueryString["lotno"];

                if (!String.IsNullOrEmpty(_gtin) && !String.IsNullOrEmpty(_lotNo))
                {
                    ItemLot o = ItemLot.GetItemLotByGtinAndLotNo(_gtin, _lotNo);

                    if (o != null)
                    {
                        ddlItemCategory.DataBind();
                        ddlItemCategory.SelectedValue = o.ItemObject.ItemCategoryId.ToString();
                        ddlItem.DataBind();
                        ddlItem.SelectedValue = o.ItemId.ToString();
                        ddlGtin.DataBind();
                        ddlGtin.SelectedValue     = o.Gtin;
                        txtLotNumber.Text         = o.LotNumber;
                        txtExpireDate.Text        = o.ExpireDate.ToString(ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat);
                        txtNotes.Text             = o.Notes;
                        rblIsActive.SelectedValue = o.IsActive.ToString();

                        gvItemLotNew.Visible = true;
                        odsItemLotNew.SelectParameters.Clear();
                        odsItemLotNew.SelectParameters.Add("gtin", _gtin);
                        odsItemLotNew.SelectParameters.Add("lotNumber", _lotNo);
                        odsItemLotNew.DataBind();
                        gvItemLotNew.DataBind();

                        btnEdit.Visible = true;
                    }
                }
                else
                {
                    gvItemLotNew.Visible = false;
                    //btnRemove.Visible = false;
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
    }
Exemplo n.º 14
0
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                int    i     = 0;
                string gtin  = Request.QueryString["gtin"];
                string lotno = Request.QueryString["lotno"];

                if (!String.IsNullOrEmpty(gtin) && !String.IsNullOrEmpty(lotno))
                {
                    ItemLot o = ItemLot.GetItemLotByGtinAndLotNo(gtin, lotno);

                    int itemId = -1;
                    if (ddlItem.SelectedIndex != -1)
                    {
                        int.TryParse(ddlItem.SelectedValue, out itemId);
                        o.ItemId = itemId;
                    }
                    if (!String.IsNullOrEmpty(ddlGtin.SelectedValue))
                    {
                        o.Gtin = ddlGtin.SelectedValue;
                    }
                    if (!String.IsNullOrEmpty(txtLotNumber.Text))
                    {
                        o.LotNumber = txtLotNumber.Text;
                    }
                    if (!String.IsNullOrEmpty(txtExpireDate.Text))
                    {
                        o.ExpireDate = DateTime.ParseExact(txtExpireDate.Text, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);
                    }
                    if (!String.IsNullOrEmpty(txtNotes.Text))
                    {
                        o.Notes = txtNotes.Text;
                    }
                    o.IsActive = bool.Parse(rblIsActive.SelectedValue);

                    i = ItemLot.Update(o);
                }
                else
                {
                    ItemLot o = new ItemLot();

                    int itemId = -1;
                    if (ddlItem.SelectedIndex != -1)
                    {
                        int.TryParse(ddlItem.SelectedValue, out itemId);
                        o.ItemId = itemId;
                    }
                    if (!String.IsNullOrEmpty(ddlGtin.SelectedValue))
                    {
                        o.Gtin = ddlGtin.SelectedValue;
                        gtin   = o.Gtin;
                    }
                    if (!String.IsNullOrEmpty(txtLotNumber.Text))
                    {
                        o.LotNumber = txtLotNumber.Text;
                        lotno       = o.LotNumber;
                    }
                    if (!String.IsNullOrEmpty(txtExpireDate.Text))
                    {
                        o.ExpireDate = DateTime.ParseExact(txtExpireDate.Text, ConfigurationDate.GetConfigurationDateById(int.Parse(Configuration.GetConfigurationByName("DateFormat").Value)).DateFormat.ToString(), CultureInfo.CurrentCulture);
                    }
                    if (!String.IsNullOrEmpty(txtNotes.Text))
                    {
                        o.Notes = txtNotes.Text;
                    }

                    i = ItemLot.Insert(o);
                }

                if (i > 0)
                {
                    ClearControls(this);
                    BindGrid(gtin, lotno);
                    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;
        }
    }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            // Concepts
            Console.WriteLine("Generating OpenIZ Concepts to support GIIS data");
            DatasetInstall conceptDataset = new DatasetInstall()
            {
                Id = "Concepts to support TIIS data", Action = new List <DataInstallAction>()
            };
            DataInsert healthFacilityTypes = new DataInsert()
            {
                Element = new ConceptSet()
                {
                    Key      = Guid.NewGuid(),
                    Mnemonic = "HealthFacilityTypes",
                    Oid      = "1.3.6.1.4.1.45219.1.3.5.99.1",
                    Name     = "Health Facility Types",
                    Url      = "http://ivd.moh.go.tz/valueset/timr/HealthFacilityTypes"
                },
                Association = new List <DataAssociation>()
            },
                       placeTypes = new DataInsert()
            {
                Element = new ConceptSet()
                {
                    Key      = Guid.NewGuid(),
                    Mnemonic = "PlaceTypes",
                    Oid      = "1.3.6.1.4.1.45219.1.3.5.99.2",
                    Name     = "Place Sub-Classifications",
                    Url      = "http://openiz.org/valueset/timr/PlaceTypes"
                },
                Association = new List <DataAssociation>()
                {
                    new DataAssociation()
                    {
                        PropertyName = "Concepts",
                        Element      = new Concept()
                        {
                            Key = PT_DISTRICT,
                            StatusConceptKey = StatusKeys.Active,
                            IsSystemConcept  = false,
                            ClassKey         = ConceptClassKeys.Other,
                            Mnemonic         = "PlaceType-District",
                            ConceptNames     = new List <ConceptName>()
                            {
                                new ConceptName()
                                {
                                    Language = "en",
                                    Name     = "District"
                                }
                            }
                        }
                    },
                    new DataAssociation()
                    {
                        PropertyName = "Concepts",
                        Element      = new Concept()
                        {
                            Key = PT_DISTRICT_COUNCIL,
                            StatusConceptKey = StatusKeys.Active,
                            IsSystemConcept  = false,
                            ClassKey         = ConceptClassKeys.Other,
                            Mnemonic         = "PlaceType-DistrictCouncil",
                            ConceptNames     = new List <ConceptName>()
                            {
                                new ConceptName()
                                {
                                    Language = "en",
                                    Name     = "District Council"
                                }
                            }
                        }
                    },
                    new DataAssociation()
                    {
                        PropertyName = "Concepts",
                        Element      = new Concept()
                        {
                            Key = PT_REGION,
                            StatusConceptKey = StatusKeys.Active,
                            IsSystemConcept  = false,
                            ClassKey         = ConceptClassKeys.Other,
                            Mnemonic         = "PlaceType-Region",
                            ConceptNames     = new List <ConceptName>()
                            {
                                new ConceptName()
                                {
                                    Language = "en",
                                    Name     = "Region"
                                }
                            }
                        }
                    },
                    new DataAssociation()
                    {
                        PropertyName = "Concepts",
                        Element      = new Concept()
                        {
                            Key = PT_TERRITORY,
                            StatusConceptKey = StatusKeys.Active,
                            IsSystemConcept  = false,
                            ClassKey         = ConceptClassKeys.Other,
                            Mnemonic         = "PlaceType-Territory",
                            ConceptNames     = new List <ConceptName>()
                            {
                                new ConceptName()
                                {
                                    Language = "en",
                                    Name     = "Territory"
                                }
                            }
                        }
                    },
                    new DataAssociation()
                    {
                        PropertyName = "Concepts",
                        Element      = new Concept()
                        {
                            Key = PT_VILLAGE,
                            StatusConceptKey = StatusKeys.Active,
                            IsSystemConcept  = false,
                            ClassKey         = ConceptClassKeys.Other,
                            Mnemonic         = "PlaceType-Village",
                            ConceptNames     = new List <ConceptName>()
                            {
                                new ConceptName()
                                {
                                    Language = "en",
                                    Name     = "Village"
                                }
                            }
                        }
                    }
                }
            };


            foreach (var itm in HealthFacilityType.GetHealthFacilityTypeList().OrderBy(o => o.Id))
            {
                facilityTypeId.Add(itm.Id, Guid.NewGuid());

                healthFacilityTypes.Association.Add(
                    new DataAssociation()
                {
                    PropertyName = "Concepts",
                    Element      = new Concept()
                    {
                        Key = facilityTypeId[itm.Id],
                        StatusConceptKey = StatusKeys.Active,
                        IsSystemConcept  = false,
                        ClassKey         = ConceptClassKeys.Other,
                        Mnemonic         = "Facility-" + itm.Name.Replace(" ", ""),
                        ConceptNames     = new List <ConceptName>()
                        {
                            new ConceptName()
                            {
                                Language = "en",
                                Name     = itm.Name
                            }
                        }
                    }
                }
                    );
            }


            (healthFacilityTypes.Element as ConceptSet).ConceptsXml = healthFacilityTypes.Association.Select(o => o.Element.Key.Value).ToList();
            (placeTypes.Element as ConceptSet).ConceptsXml          = placeTypes.Association.Select(o => o.Element.Key.Value).ToList();
            conceptDataset.Action.AddRange(healthFacilityTypes.Association.Select(o => new DataInsert()
            {
                Element = o.Element
            }));
            conceptDataset.Action.AddRange(placeTypes.Association.Select(o => new DataInsert()
            {
                Element = o.Element
            }));
            conceptDataset.Action.AddRange(new DataInstallAction[]
            {
                new DataInsert()
                {
                    Element = new Concept()
                    {
                        Key = industryManufacturer, Mnemonic = "Industry-Manufacturing", ClassKey = ConceptClassKeys.Other, IsSystemConcept = false, StatusConceptKey = StatusKeys.Active, ConceptNames = new List <ConceptName>()
                        {
                            new ConceptName()
                            {
                                Language = "en", Name = "Manufacturing"
                            }
                        }, ConceptSetsXml = new List <Guid>()
                        {
                            Guid.Parse("d1597e50-845a-46e1-b9ae-6f99ff93d9db")
                        }
                    }
                },
                new DataInsert()
                {
                    Element = new Concept()
                    {
                        Key = industryOther, Mnemonic = "Industry-OtherUnknown", ClassKey = ConceptClassKeys.Other, IsSystemConcept = false, StatusConceptKey = StatusKeys.Active, ConceptNames = new List <ConceptName>()
                        {
                            new ConceptName()
                            {
                                Language = "en", Name = "Other/Unknown"
                            }
                        }, ConceptSetsXml = new List <Guid>()
                        {
                            Guid.Parse("d1597e50-845a-46e1-b9ae-6f99ff93d9db")
                        }
                    }
                },
                new DataInsert()
                {
                    Element = new Concept()
                    {
                        Key = industryHealthDelivery, Mnemonic = "Industry-HealthDelivery", ClassKey = ConceptClassKeys.Other, IsSystemConcept = false, StatusConceptKey = StatusKeys.Active, ConceptNames = new List <ConceptName>()
                        {
                            new ConceptName()
                            {
                                Language = "en", Name = "Healthcare"
                            }
                        }, ConceptSetsXml = new List <Guid>()
                        {
                            Guid.Parse("d1597e50-845a-46e1-b9ae-6f99ff93d9db")
                        }
                    }
                }
            });
            healthFacilityTypes.Association.Clear();
            placeTypes.Association.Clear();
            conceptDataset.Action.Add(healthFacilityTypes);
            conceptDataset.Action.Add(placeTypes);

            // Facilities
            Console.WriteLine("Exporting GIIS Facilities to OpenIZ IMS Format");
            DatasetInstall facilityDataset = new DatasetInstall()
            {
                Action = new List <DataInstallAction>()
            };

            facilityDataset.Id = "Facilities from GIIS";
            foreach (var itm in HealthFacility.GetHealthFacilityList().OrderBy(o => o.Id))
            {
                facilityDataset.Action.Add(new DataInsert()
                {
                    Element = MapFacility(itm)
                });
            }

            // Places
            Console.WriteLine("Exporting GIIS Places to OpenIZ IMS Format");
            DatasetInstall placeDataset = new DatasetInstall()
            {
                Action = new List <DataInstallAction>()
            };

            placeDataset.Id = "Places from GIIS";
            foreach (var itm in GIIS.DataLayer.Place.GetPlaceList().OrderBy(o => o.ParentId))
            {
                placeDataset.Action.Add(new DataInsert()
                {
                    Element = MapPlace(itm)
                });
            }

            // Users
            Console.WriteLine("Exporting GIIS Users to OpenIZ IMS Format");
            DatasetInstall userDataset = new DatasetInstall()
            {
                Action = new List <DataInstallAction>()
            };

            userDataset.Id = "Users from TIIS";
            foreach (var itm in User.GetUserList())
            {
                if (userDataset.Action.Any(o => (o.Element as SecurityUser)?.UserName.Trim().ToLower() == itm.Username.Trim().ToLower()) ||
                    itm.Username.ToLower() == "administrator")
                {
                    continue; /// Apparently user names are distinct based on case?
                }
                Guid userId = Guid.NewGuid(), entityId = Guid.NewGuid();
                userMap.Add(itm.Id, userId);

                if (!userEntityMap.TryGetValue(itm.Id, out entityId))
                {
                    entityId = Guid.NewGuid();
                    userEntityMap.Add(itm.Id, entityId);
                }
                var securityUser = new SecurityUser()
                {
                    Key              = userId,
                    UserName         = itm.Username,
                    Email            = itm.Email,
                    EmailConfirmed   = !String.IsNullOrEmpty(itm.Email),
                    LastLoginTime    = itm.Lastlogin,
                    SecurityHash     = Guid.Empty.ToString(),
                    Lockout          = itm.IsActive ? null : (DateTime?)DateTime.MaxValue,
                    PasswordHash     = BitConverter.ToString(Convert.FromBase64String(itm.Password)).Replace("-", ""),
                    UserClass        = UserClassKeys.HumanUser,
                    TwoFactorEnabled = false,
                    ObsoletionTime   = itm.Deleted ? (DateTime?)DateTime.Now : null,
                    ObsoletedByKey   = itm.Deleted ? (Guid?)Guid.Parse(AuthenticationContext.SystemUserSid) : null,
                };
                var userEntity = new UserEntity()
                {
                    Key   = entityId,
                    Names = new List <EntityName>()
                    {
                        new EntityName(NameUseKeys.OfficialRecord, itm.Lastname, itm.Firstname)
                    },

                    SecurityUserKey = userId,
                    Identifiers     = new List <EntityIdentifier>()
                    {
                        new EntityIdentifier(new AssigningAuthority("TIIS_USER_ID", "TIIS User Identifiers", "1.3.6.1.4.1.45219.1.3.5.2"), itm.Id.ToString())
                    },
                    Tags = new List <EntityTag>()
                    {
                        new EntityTag("http://openiz.org/tags/contrib/importedData", "true")
                    },
                    StatusConceptKey = itm.IsActive ? StatusKeys.Active : StatusKeys.Obsolete
                };
                if (!String.IsNullOrEmpty(itm.Email))
                {
                    userEntity.Telecoms = new List <EntityTelecomAddress>()
                    {
                        new EntityTelecomAddress(TelecomAddressUseKeys.WorkPlace, itm.Email)
                    }
                }
                ;

                Guid facilityId = Guid.Empty;
                if (facilityMap.TryGetValue(itm.HealthFacilityId, out facilityId))
                {
                    userEntity.Relationships.Add(new EntityRelationship(EntityRelationshipTypeKeys.Employee, new Entity()
                    {
                        Key = facilityId
                    }));
                }

                // data element
                var securityUserData = new DataInsert()
                {
                    Element     = securityUser,
                    Association = new List <DataAssociation>()
                };

                // Role
                foreach (var r in Role.GetRolesOfUser(itm.Id))
                {
                    Guid roleId = Guid.Empty;
                    if (!roleMap.TryGetValue(r.Id, out roleId))
                    {
                        roleId = Guid.NewGuid();
                        roleMap.Add(r.Id, roleId);
                    }

                    var role = new SecurityRole()
                    {
                        Key            = roleId,
                        Name           = r.Name,
                        ObsoletionTime = r.IsActive ? null : (DateTime?)DateTime.Now,
                        ObsoletedByKey = r.IsActive ? null : (Guid?)Guid.Parse(AuthenticationContext.SystemUserSid)
                    };

                    // Add roles to the user
                    securityUserData.Association.Add(new DataAssociation()
                    {
                        PropertyName = "Roles",
                        Element      = new SecurityRole()
                        {
                            Key = role.Key
                        }
                    });

                    // Add role
                    userDataset.Action.Add(new DataInsert()
                    {
                        Element = role
                    });

                    // Vaccinator?
                    if (r.Name == "Vaccinator")
                    {
                        // Provider entity
                        var providerEntity = new Provider()
                        {
                            Key         = Guid.NewGuid(),
                            Names       = userEntity.Names,
                            Telecoms    = userEntity.Telecoms,
                            Identifiers = userEntity.Identifiers.Select(o => new EntityIdentifier(new AssigningAuthority("PROVIDER_ID", "TImR Assigned Provider ID", "1.3.6.1.4.1.45219.1.3.5.80"), o.Value)).ToList(),
                            Tags        = new List <EntityTag>()
                            {
                                new EntityTag("http://openiz.org/tags/contrib/importedData", "true")
                            },
                            StatusConceptKey = itm.IsActive ? StatusKeys.Active : StatusKeys.Obsolete
                        };
                        userDataset.Action.Add(new DataInsert()
                        {
                            Element = providerEntity
                        });

                        // Create a heath care provider
                        userEntity.Relationships.Add(new EntityRelationship()
                        {
                            RelationshipTypeKey = EntityRelationshipTypeKeys.AssignedEntity,
                            TargetEntityKey     = providerEntity.Key
                        });
                    }
                }


                userDataset.Action.Add(securityUserData);
                userDataset.Action.Add(new DataInsert()
                {
                    Element = userEntity
                });
            }

            var materialDataset = new DatasetInstall()
            {
                Id = "Manufactured Materials from GIIS"
            };

            foreach (var il in ItemLot.GetItemLotList())
            {
                var itm = MapMaterial(il, materialDataset);
                materialDataset.Action.Add(new DataUpdate()
                {
                    InsertIfNotExists = true, Element = itm
                });
            }


            // Write datasets
            XmlSerializer xsz = new XmlSerializer(typeof(DatasetInstall));

            using (var fs = File.Create("990-tiis.concepts.dataset"))
                xsz.Serialize(fs, conceptDataset);
            using (var fs = File.Create("991-tiis.facilities.dataset"))
                xsz.Serialize(fs, facilityDataset);
            using (var fs = File.Create("992-tiis.places.dataset"))
                xsz.Serialize(fs, placeDataset);
            using (var fs = File.Create("993-tiis.users.dataset"))
                xsz.Serialize(fs, userDataset);
            using (var fs = File.Create("994-tiis.materials.dataset"))
                xsz.Serialize(fs, materialDataset);
        }
    }
        /// <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);
        }
Exemplo n.º 17
0
        public StorePackage(Storage storage, Worker worker)
        {
            Console.Clear();


            Line("=========== Store Packages Procedure ============");
            Console.WriteLine();

            Line("================ Pending Items: =================");
            Console.WriteLine();

            storage.PrintPending();

            Line("===== Type IDs of items to Store or E(xit): =====");
            Console.Write("== IDs to Store: ");
            string input = Console.ReadLine();

            Line();

            if (input.ToUpper() == "E")
            {
                return;
            }

            Console.WriteLine();

            if (input.Split(',').Length == 0)
            {
                Console.WriteLine($"================ Ordem Vazia ===================");
                return;
            }

            Line("======== Creating order with these items: =======");

            Console.WriteLine();

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

            foreach (string itemS in input.Split(','))
            {
                try
                {
                    int     id   = Convert.ToInt32(itemS);
                    ItemLot item = storage.ItemById(id);
                    items.Add(item);
                }
                catch
                {
                    Console.WriteLine($"========= {itemS} não é um ID válido ===========");
                    return;
                }
            }

            var table = items.ToStringTable
                        (
                new[] { "ItemLot ID", "Cod. Barras", "Quantidade", "Categoria" },
                u => u.Id,
                u => u.Merchandise.BarCode,
                u => u.Quantity,
                u => u.Category.Name
                        );

            Console.WriteLine(table);

            Line("====== Press C to Confirm or other to Abort =====");

            string confirmation = Console.ReadLine();

            if (confirmation.ToUpper() == "C")
            {
                string[] charIds = input.Split(',');
                int[]    ids     = new int[charIds.Length];

                for (int i = 0; i < ids.Length; i++)
                {
                    ids[i] = Convert.ToInt32(charIds[i]);
                }

                Order order = storage.CreateStorageOrder(ids, worker);

                if (order == null)
                {
                    Line("=========== NÃO FOI POSSÍVEL ARMAZENAR ==========");
                }

                else
                {
                    Line($"=========== Instruções p/ Ordem {order.Id} ===============");
                    Console.WriteLine();
                    order.WriteInstructionsToConsole();
                }

                // Save State
                JSON.WriteToJsonFile("../../../data.json", storage);
            }

            else
            {
                Line("=============== Operation Aborted ===============");
                return;
            }
        }
Exemplo n.º 18
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
                });
            }
        }
        /// <summary>
        /// Updates the specified <paramref name="orderLine"/> based on business rules
        /// </summary>
        /// <param name="orderLine">The <see cref="T:GIIS.DataLayer.TransferOrderDetail"/> line to be updated</param>
        /// <returns>The <see cref="T:GIIS.DataLayer.TransferOrderDetail"/> which was updated</returns>
        /// <remarks>
        /// <list type="ordered">
        /// <item><description>	Load the current order line for the database using the order line #</description></item>
        /// <item><description>	Instantiate an instance of StockManagementLogic BLL class.</description></item>
        /// <item><description>	If the status of the current order line is:
        ///     <list type="table">
        ///         <listHeader>
        ///             <term>State</term>
        ///             <description>Actions</description>
        ///         </listHeader>
        ///         <item>
        ///             <term>Requested</term>
        ///             <description>
        ///                 <list type="ordered">
        ///                     <item><description>[Guard Condition] Ensure the new state is either “Cancelled”, “Requested” or “Released” otherwise throw an invalid state transition exception</description></item>
        ///                     <item><description>Update the quantity and status of the  order detail item</description></item>
        ///                     <item><description>If the new state is “Released” then call the Allocate function of the StockManagementLogic instance to allocate the specified order detail.</description></item>
        ///                     <item><description>Save the order detail</description></item>
        ///                 </list>
        ///             </description>
        ///         </item>
        ///         <item>
        ///             <term>Released</term>
        ///             <description>
        ///                 <list type="ordered">
        ///                     <item><description>[Guard Condition] Ensure the new state is either “Cancelled”, “Released” or “Packed” otherwise thrown an invalid state transition exception</description></item>
        ///                     <item><description>If the current state is “Released” then
        ///                         <list type="ordered">
        ///                             <item><description>Calculate the difference in quantity from the “old” record and “new” record</description></item>
        ///                             <item><description>Call the Allocate method of the StockManagementLogic instance to perform the additional allocation/de-allocation.</description></item>
        ///                         </list>
        ///                     </description></item>
        ///                     <item><description>	Update the quantity and status of the order detail item.</description></item>
        ///                     <item><description>If the new state is “Cancelled” then call the Allocate method of the StockManagementLogic instance to perform the de-allocation of the item.</description></item>
        ///                     <item><description>Save the order detail</description></item>
        ///                 </list>
        ///             </description>
        ///         </item>
        ///         <item>
        ///             <term>Packed</term>
        ///             <description>
        ///                 <list type="ordered">
        ///                     <item><description>[Guard Condition] Ensure the new state is either “Cancelled”, “Packed” or “Shipped”</description></item>
        ///                     <item><description>Update the quantity and status of the order detail item.</description></item>
        ///                     <item><description>If the new state is “cancelled” then call the Allocate method of the StockManagementLogic instance to perform the de-allocation of the item.</description></item>
        ///                     <item><description>If the new state is “Shipped” then
        ///                         <list type="ordered">
        ///                             <item><description>Call the allocate method of the StockManagementLogic instance to perform the de-allocation of the line item.</description></item>
        ///                             <item><description>Call the Transfer method of the StockManagementLogic instance to perform the transfer transactions between the source and target facilities.</description></item>
        ///                         </list>
        ///                     </description></item>
        ///                     <item><description>Save the order detail</description></item>
        ///                 </list>
        ///             </description>
        ///         </item>
        ///         <item>
        ///             <term>Shipped</term>
        ///             <description>Throw an invalid operation exception as shipped orders (and their lines) cannot be edited</description>
        ///         </item>
        ///         <item>
        ///             <term>Cancelled</term>
        ///             <description>Throw an invalid operation exception as cancelled orders (and their lines) cannot be edited</description>
        ///         </item>
        ///     </list>
        /// </description></item>
        /// </list>
        /// </remarks>
        public TransferOrderDetail UpdateOrderLine(TransferOrderDetail orderLine, Int32 modifiedBy)
        {
            if (orderLine == null)
            {
                throw new ArgumentNullException("orderLine");
            }
            else if (orderLine.OrderDetailNum == default(Int32))
            {
                throw new ArgumentException("Order line is not saved", "orderLine");
            }

            // Load the current order line from the database
            TransferOrderDetail currentOrderLine   = TransferOrderDetail.GetTransferOrderDetailByOrderDetailNum(orderLine.OrderDetailNum);
            TransferOrderHeader currentOrderHeader = TransferOrderHeader.GetTransferOrderHeaderByOrderNum(orderLine.OrderNum);

            // Can't change the GTIN with this function
            if (orderLine.OrderGtin != currentOrderLine.OrderGtin)
            {
                throw new InvalidOperationException("Cannot change the GTIN with this function. Remove the order line first and add another order-line with the new GTIN");
            }

            // New order lot number is null?  We need to get oldest lot
            if (String.IsNullOrEmpty(orderLine.OrderGtinLotnum) || orderLine.OrderGtinLotnum == "*")
            {
                ItemLot itemLot = GetOldestLot(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin); //currentOrderLine.OrderGtinLotnum;
                if (itemLot != null)
                {
                    orderLine.OrderGtinLotnum = itemLot.LotNumber;
                }
            }

            StockManagementLogic stockLogic = new StockManagementLogic();

            // Apply rules
            switch ((OrderStatusType)currentOrderLine.OrderDetailStatus)
            {
            case OrderStatusType.Requested:
                // State transitions
                if (orderLine.OrderDetailStatus != (int)OrderStatusType.Cancelled &&
                    orderLine.OrderDetailStatus != (int)OrderStatusType.Released &&
                    orderLine.OrderDetailStatus != (int)OrderStatusType.Requested)
                {
                    throw new IllegalStateException((OrderStatusType)orderLine.OrderDetailStatus, "TransferOrderDetail", "UpdateOrderLine");
                }

                // Allocate the data if this is a transition
                if (orderLine.OrderDetailStatus == (int)OrderStatusType.Released)
                {
                    stockLogic.Allocate(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, (int)orderLine.OrderQty, orderLine, modifiedBy);
                }

                break;

            case OrderStatusType.Released:

                // Guard conditions
                if (orderLine.OrderDetailStatus != (int)OrderStatusType.Cancelled &&
                    orderLine.OrderDetailStatus != (int)OrderStatusType.Released &&
                    orderLine.OrderDetailStatus != (int)OrderStatusType.Packed)
                {
                    throw new IllegalStateException((OrderStatusType)orderLine.OrderDetailStatus, "TransferOrderDetail", "UpdateOrderLine");
                }

                // We need to adjust the allocations?
                if (currentOrderLine.OrderQty != orderLine.OrderQty)
                {
                    stockLogic.Allocate(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, (int)(orderLine.OrderQty - currentOrderLine.OrderQty), orderLine, modifiedBy);
                }

                // Released -> Cancelled = Deallocate
                if (orderLine.OrderDetailStatus == (int)OrderStatusType.Cancelled)
                {
                    stockLogic.Allocate(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, -(int)orderLine.OrderQty, orderLine, modifiedBy);
                }

                break;

            case OrderStatusType.Packed:
                // Guard conditions
                if (orderLine.OrderDetailStatus != (int)OrderStatusType.Cancelled &&
                    orderLine.OrderDetailStatus != (int)OrderStatusType.Packed &&
                    orderLine.OrderDetailStatus != (int)OrderStatusType.Shipped)
                {
                    throw new IllegalStateException((OrderStatusType)orderLine.OrderDetailStatus, "TransferOrderDetail", "UpdateOrderLine");
                }

                // We need to adjust the allocations?
                if (currentOrderLine.OrderQty != orderLine.OrderQty)
                {
                    stockLogic.Allocate(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, (int)(orderLine.OrderQty - currentOrderLine.OrderQty), orderLine, modifiedBy);
                }

                // Packed -> Cancelled = Deallocate
                if (orderLine.OrderDetailStatus == (int)OrderStatusType.Cancelled)
                {
                    stockLogic.Allocate(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, -(int)orderLine.OrderQty, orderLine, modifiedBy);
                }
                // Packed -> Shipped = Deallocate then Transfer
                else if (orderLine.OrderDetailStatus == (int)OrderStatusType.Shipped)
                {
                    stockLogic.Allocate(currentOrderHeader.OrderFacilityFromObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, -(int)orderLine.OrderQty, orderLine, modifiedBy);
                    stockLogic.Transfer(currentOrderHeader.OrderFacilityFromObject, currentOrderHeader.OrderFacilityToObject, orderLine.OrderGtin, orderLine.OrderGtinLotnum, orderLine, (int)orderLine.OrderQty, modifiedBy);
                }

                break;

            case OrderStatusType.Shipped:
                throw new InvalidOperationException("Shipped orders cannot be modified " + orderLine.OrderDetailNum.ToString());

            case OrderStatusType.Cancelled:
                throw new InvalidOperationException("Cancelled orders cannot be modified");
            }

            // Update
            orderLine.ModifiedBy = modifiedBy;
            orderLine.ModifiedOn = DateTime.Now;
            TransferOrderDetail.Update(orderLine);

            // Return the order line
            return(orderLine);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.Page.IsPostBack)
        {
            if (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["Child-dictionary" + language];
                if (wtList == null)
                {
                    List <WordTranslate> wordTranslateList = WordTranslate.GetWordByLanguage(languageId, "Child");
                    wtList = new Dictionary <string, string>();
                    foreach (WordTranslate vwt in wordTranslateList)
                    {
                        wtList.Add(vwt.Code, vwt.Name);
                    }
                    HttpContext.Current.Cache.Insert("Child-dictionary" + language, wtList);
                }
                #region Person Configuration

                List <PersonConfiguration> pcList = PersonConfiguration.GetPersonConfigurationList();

                foreach (PersonConfiguration pc in pcList)
                {
                    if (pc.IsVisible == false)
                    {
                        Control lbl = FindMyControl(this, "lbl" + pc.ColumnName);
                        Control txt = FindMyControl(this, "txt" + pc.ColumnName);
                        Control tr  = FindMyControl(this, "tr" + pc.ColumnName);

                        if (lbl != null)
                        {
                            lbl.Visible = false;
                        }

                        if (txt != null)
                        {
                            txt.Visible = false;
                        }



                        if (tr != null)
                        {
                            tr.Visible = false;
                        }

                        for (int i = 1; i < gvChild.Columns.Count; i++)
                        {
                            if (gvChild.Columns[i].HeaderText == pc.ColumnName)
                            {
                                gvChild.Columns[i].Visible = false;
                                break;
                            }
                        }
                    }
                }
                string id1 = Configuration.GetConfigurationByName("IdentificationNo1").Value;
                string id2 = Configuration.GetConfigurationByName("IdentificationNo2").Value;
                string id3 = Configuration.GetConfigurationByName("IdentificationNo3").Value;
                #endregion

                this.lbHealthFacility.Text = wtList["ImmunizedChildrenByLotHealthFacility"];
                this.lbLotId.Text          = wtList["ImmunizedChildrenByLotItemLot"];
                this.lbChildNo.Text        = wtList["ImmunizedChildrenByLotChildrenNo"];

                this.lblTitle.Text = wtList["PrintImmunizedChildrenByLotPageTitle"];

                //grid header text
                #region Grid Columns
                gvChild.Columns[1].HeaderText  = wtList["ChildSystem"];
                gvChild.Columns[2].HeaderText  = wtList["ChildFirstname1"];
                gvChild.Columns[3].HeaderText  = wtList["ChildFirstname2"];
                gvChild.Columns[4].HeaderText  = wtList["ChildLastname1"];
                gvChild.Columns[5].HeaderText  = wtList["ChildLastname2"];
                gvChild.Columns[6].HeaderText  = wtList["ChildBirthdate"];
                gvChild.Columns[7].HeaderText  = wtList["ChildGender"];
                gvChild.Columns[8].HeaderText  = wtList["ChildHealthcenter"];
                gvChild.Columns[9].HeaderText  = wtList["ChildBirthplace"];
                gvChild.Columns[10].HeaderText = wtList["ChildCommunity"];
                gvChild.Columns[11].HeaderText = wtList["ChildDomicile"];
                gvChild.Columns[12].HeaderText = wtList["ChildStatus"];
                gvChild.Columns[13].HeaderText = wtList["ChildAddress"];
                gvChild.Columns[14].HeaderText = wtList["ChildPhone"];
                gvChild.Columns[15].HeaderText = wtList["ChildMobile"];
                gvChild.Columns[16].HeaderText = wtList["ChildEmail"];
                gvChild.Columns[17].HeaderText = wtList["ChildMother"];
                gvChild.Columns[18].HeaderText = wtList["ChildMotherFirstname"];
                gvChild.Columns[19].HeaderText = wtList["ChildMotherLastname"];
                gvChild.Columns[20].HeaderText = wtList["ChildFather"];
                gvChild.Columns[21].HeaderText = wtList["ChildFatherFirstname"];
                gvChild.Columns[22].HeaderText = wtList["ChildFatherLastname"];
                gvChild.Columns[23].HeaderText = wtList["ChildCaretaker"];
                gvChild.Columns[24].HeaderText = wtList["ChildCaretakerFirstname"];
                gvChild.Columns[25].HeaderText = wtList["ChildCaretakerLastname"];
                gvChild.Columns[26].HeaderText = wtList["ChildNotes"];
                gvChild.Columns[27].HeaderText = wtList["ChildIsActive"];
                gvChild.Columns[30].HeaderText = id1;
                gvChild.Columns[31].HeaderText = id2;
                gvChild.Columns[32].HeaderText = id3;

                #endregion

                int    hfId  = CurrentEnvironment.LoggedUser.HealthFacilityId;
                string _hfId = (string)Request.QueryString["hfId"];
                if (!String.IsNullOrEmpty(_hfId))
                {
                    int.TryParse(_hfId, out hfId);
                }

                int lotId = 0;
                lotId = Helper.ConvertToInt(HttpContext.Current.Session["ImmunizedChildrenByLot-lotID"].ToString());

                lblHealthFacility.Text = HealthFacility.GetHealthFacilityById(hfId).Name;
                if (lotId != 0)
                {
                    lblLotId.Text = ItemLot.GetItemLotById(lotId).LotNumber;
                }
                lblChildNo.Text = Child.GetCountImmunizedChildrenByLot(hfId, lotId).ToString();
                int maximumRows   = int.MaxValue;
                int startRowIndex = 0;

                List <Child> list = Child.GetImmunizedChildrenByLot(ref maximumRows, ref startRowIndex, hfId, lotId);
                gvChild.DataSource = list;
                gvChild.DataBind();
            }
            else
            {
                Response.Redirect("Default.aspx", false);
            }
        }
    }
Exemplo n.º 21
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);
        }
        /// <summary>
        /// Add an order line to the order defined by <paramref name="order"/>
        /// </summary>
        /// <param name="order">The order to which the line should be added</param>
        /// <param name="gtin">The global trade identification number of the item in the line</param>
        /// <param name="lot">(Optional) The lot number to be used. Note if null is passed in <paramref name="lot"/> then the oldest lot is used first</param>
        /// <param name="qty">The quantity of the item to be added to the order</param>
        /// <param name="uom">(Optional) The base unit of measure. If <paramref name="uom"/> is null then the default UOM for the item described by <paramref name="gtin"/> is used</param>
        /// <returns>The constructed and saved <see cref="T:GIIS.DataLayer.TransferOrderDetail"/></returns>
        /// <remarks>
        /// The add order line function is responsible for adding a new order line to the order detail. This function operates in the following manner:
        /// <list type="ordered">
        /// <item>
        ///     <description>[Guard Condition] If the order passed into the function IS in the “Packed” or “Shipped” state then throw an invalid state exception (sanity check)</description>
        /// </item>
        /// <item>
        ///     <description>Lookup the item by the GTIN provided in the function call.</description>
        /// </item>
        /// <item>
        ///     <description>[Guard Condition] If the lot number is provided, and the lot number is not a valid lot number for the item provided then throw an error code</description>
        /// </item>
        /// <item>
        ///     <description>If the current status of the order to which the detail is to be attached is “Released” then
        ///         <list type="ordered">
        ///             <item>
        ///                 <description>Instantiate a StockManagementLogic BLL class</description>
        ///             </item>
        ///             <item>Allocate the stock using the Allocate method</item>
        ///         </list>
        ///     </description>
        /// </item>
        /// <item>
        ///     <description>Set the unit of measure, quantity, gtin, etc. fields of the TransferOrderDetail instance to the parameters and fields derived from loaded Item.</description>
        /// </item>
        /// <item>
        ///     <description>Save the order line.</description>
        /// </item>
        ///</list>
        /// </remarks>
        public TransferOrderDetail AddOrderLine(TransferOrderHeader order, String gtin, String lot, Int32 qty, Uom uom, Int32 modifiedBy)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }
            if (String.IsNullOrEmpty(gtin))
            {
                throw new ArgumentNullException("gtin");
            }

            // Sanity check
            if (order.OrderStatus == (int)OrderStatusType.Shipped ||
                order.OrderStatus == (int)OrderStatusType.Cancelled)
            {
                throw new IllegalStateException((OrderStatusType)order.OrderStatus, "TransferOrderHeader", "AddOrderLine");
            }

            // Lookup item by GTIN and optionally lot
            ItemLot item = null;

            if (!String.IsNullOrEmpty(lot))
            {
                item = ItemLot.GetItemLotByGtinAndLotNo(gtin, lot);
            }
            if (item == null)
            {               // not found - We get the item by lot
                item = ItemLot.GetItemLotByGtin(gtin);
                lot  = "*"; // null;
            }

            // Item still null?
            if (item == null)
            {
                throw new InvalidOperationException(String.Format("Cannot locate item with GTIN {0}", gtin));
            }

            // Construct the order detail
            TransferOrderDetail retVal = new TransferOrderDetail()
            {
                ModifiedBy             = modifiedBy,
                ModifiedOn             = DateTime.Now,
                OrderCustomItem        = false,
                OrderDetailDescription = item.ItemObject.Name,
                OrderDetailStatus      = order.OrderStatus,
                OrderGtin         = gtin,
                OrderGtinLotnum   = lot,
                OrderNum          = order.OrderNum,
                OrderQty          = qty,
                OrderQtyInBaseUom = qty,
                OrderUom          = uom.Name
            };

            // HACK: Overcome lack of transaction processing we have to be careful about how we do this
            ItemTransaction allocateTransaction = null;

            // Current state of order is released? We need to allocate this line item
            if (order.OrderStatus == (int)OrderStatusType.Released)
            {
                StockManagementLogic stockLogic = new StockManagementLogic();
                // We need to release this order ... If the lot was null we'll use the oldest lot number
                if (String.IsNullOrEmpty(lot))
                {
                    item = this.GetOldestLot(order.OrderFacilityFromObject, gtin);
                }

                // Allocation of specified lot
                allocateTransaction = stockLogic.Allocate(order.OrderFacilityFromObject, gtin, item.LotNumber, qty, null, modifiedBy);

                // Update order
                retVal.OrderGtinLotnum = item.LotNumber;
            }

            // Save
            retVal.OrderDetailNum = TransferOrderDetail.Insert(retVal);

            // HACK: Update the allocate transaction. This would be cleaned up with a transaction to back out changes (basically do the order detail then allocate)
            if (allocateTransaction != null)
            {
                allocateTransaction.RefId    = retVal.OrderNum.ToString();
                allocateTransaction.RefIdNum = retVal.OrderDetailNum;
                ItemTransaction.Update(allocateTransaction);
            }

            return(retVal);
        }