示例#1
0
 public Output Reify(
     Cell<IMaybe<Size>> size,
     Stream<MouseEvent> sMouse, Stream<KeyEvent> sKey,
     Cell<long> focus, Supply idSupply)
 {
     return this.reify(size, sMouse, sKey, focus, idSupply);
 }
示例#2
0
 ///<summary>Inserts one Supply into the database.  Returns the new priKey.</summary>
 internal static long Insert(Supply supply)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         supply.SupplyNum=DbHelper.GetNextOracleKey("supply","SupplyNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(supply,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     supply.SupplyNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(supply,false);
     }
 }
示例#3
0
 ///<summary>Inserts one Supply into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(Supply supply,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         supply.SupplyNum=ReplicationServers.GetKey("supply","SupplyNum");
     }
     string command="INSERT INTO supply (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="SupplyNum,";
     }
     command+="SupplierNum,CatalogNumber,Descript,Category,ItemOrder,LevelDesired,IsHidden,Price) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(supply.SupplyNum)+",";
     }
     command+=
              POut.Long  (supply.SupplierNum)+","
         +"'"+POut.String(supply.CatalogNumber)+"',"
         +"'"+POut.String(supply.Descript)+"',"
         +    POut.Long  (supply.Category)+","
         +    POut.Int   (supply.ItemOrder)+","
         +    POut.Float (supply.LevelDesired)+","
         +    POut.Bool  (supply.IsHidden)+","
         +"'"+POut.Double(supply.Price)+"')";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         supply.SupplyNum=Db.NonQ(command,true);
     }
     return supply.SupplyNum;
 }
示例#4
0
        public void Play(Player p, Supply s)
        {
            //Player gains the first two treasures
            var discards = new List<Card>();
            int numTreasuresAdded = 0;

            Card card;
            do
            {
                card = p.PopDeck();
                if (card is ITreasureCard)
                {
                    numTreasuresAdded++;
                    p.PutInHand(card);
                }
                else
                {
                    discards.Add(card);
                }

            } while (numTreasuresAdded < 2 && card != null);

            foreach (Card c in discards)
            {
                p.Gain(c);
            }
        }
示例#5
0
		public Table(Game game, int numPlayers)
			: this(game)
		{
			_NumPlayers = numPlayers;

			int multiplier = _NumPlayers >= 5 ? 2 : 1;
			Copper = new Supply(game, null, Cards.Universal.TypeClass.Copper, 60 * multiplier);
			Silver = new Supply(game, null, Cards.Universal.TypeClass.Silver, 40 * multiplier);
			Gold = new Supply(game, null, Cards.Universal.TypeClass.Gold, 30 * multiplier);

			int extraProvinceCards = 0;
			switch (_NumPlayers)
			{
				case 1:
				case 2:
					_BaseVictoryCards = 8;
					break;
				case 5:
					extraProvinceCards = 3;
					break;
				case 6:
					extraProvinceCards = 6;
					break;
			}
			Estate = new Supply(game, null, Cards.Universal.TypeClass.Estate, 3 * _NumPlayers + _BaseVictoryCards);
			Duchy = new Supply(game, null, Cards.Universal.TypeClass.Duchy, _BaseVictoryCards);
			Province = new Supply(game, null, Cards.Universal.TypeClass.Province, _BaseVictoryCards + extraProvinceCards);

			Curse = new Supply(game, null, Cards.Universal.TypeClass.Curse, 10 * Math.Max(_NumPlayers - 1, 1));
		}
		public override void Setup(Game game, Supply supply)
		{
			base.Setup(game, supply);

			Supply blackMarketSupply = new Supply(game, game.Players, TypeClass.BlackMarketSupply, Visibility.All);
			blackMarketSupply.FullSetup();
			game.Table.SpecialPiles.Add(TypeClass.BlackMarketSupply, blackMarketSupply);
		}
示例#7
0
 public ViewSupplyView(Supply supply)
 {
     InitializeComponent();
     supplyBindingSource.DataSource = supply;
     gridControl_SupplyItems.DataSource = supply.SupplyItems;
     var totalSpent = supply.SupplyItems.Select(item => item.TotalSpent).Sum();
     if (totalSpent.HasValue != true) totalSpent = 0;
     label_TotalSpent.Text = string.Format("{0:0,#} CFA", totalSpent);
 }
示例#8
0
		public override void Finalize(Game game, Supply supply)
		{
			base.Finalize(game, supply);
			foreach (Player player in game.Players)
			{
				if (!player.TokenPiles.ContainsKey(TypeClass.CoinToken))
					player.TokenPiles[TypeClass.CoinToken] = new TokenCollection();
				player.AddToken(new CoinToken());
			}
		}
示例#9
0
 public GameState GetState(Player p, Supply s)
 {
     if (p.GetHandCards().Count == 0)
     {
         return ActionState.NextState(p, s);
     }
     else
     {
         return new CellarGameState(p, s);
     }
 }
示例#10
0
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<Supply> TableToList(DataTable table){
			List<Supply> retVal=new List<Supply>();
			Supply supply;
			for(int i=0;i<table.Rows.Count;i++) {
				supply=new Supply();
				supply.SupplyNum    = PIn.Long  (table.Rows[i]["SupplyNum"].ToString());
				supply.SupplierNum  = PIn.Long  (table.Rows[i]["SupplierNum"].ToString());
				supply.CatalogNumber= PIn.String(table.Rows[i]["CatalogNumber"].ToString());
				supply.Descript     = PIn.String(table.Rows[i]["Descript"].ToString());
				supply.Category     = PIn.Long  (table.Rows[i]["Category"].ToString());
				supply.ItemOrder    = PIn.Int   (table.Rows[i]["ItemOrder"].ToString());
				supply.LevelDesired = PIn.Float (table.Rows[i]["LevelDesired"].ToString());
				supply.IsHidden     = PIn.Bool  (table.Rows[i]["IsHidden"].ToString());
				supply.Price        = PIn.Double(table.Rows[i]["Price"].ToString());
				retVal.Add(supply);
			}
			return retVal;
		}
示例#11
0
        public Game()
        {
            player = new Player();
            supply = new Supply();

            for(int i =0; i < 7; i++)
            {
                player.Gain( supply.Release("Copper"));
            }
            Card e = new Estate();
            for(int i =0; i < 3; i++)
            {
                player.Gain( e );
            }

            gameState = new GameStateContext(player, supply);
            gameState.StateChange += () =>
                {
                    OnStateChange();
                };

            player.NewHand();
        }
示例#12
0
 /// <summary>
 /// 保存
 /// </summary>
 public override void Save()
 {
     if(!m_Loaded)//新增
     {
         Supply supply=new Supply();
         SaveToDb(this, supply,true);
     }
     else//修改
     {
         Supply supply=new Supply(supplyId);
         if(supply.IsNew)
             throw new AppException("该数据已经不存在了");
         SaveToDb(this, supply,false);
     }
 }
示例#13
0
 //数据持久化
 internal static void SaveToDb(SupplyInfo pSupplyInfo, Supply  pSupply,bool pIsNew)
 {
     pSupply.SupplyId = pSupplyInfo.supplyId;
      		pSupply.SupplyName = pSupplyInfo.supplyName;
      		pSupply.SheetNum = pSupplyInfo.sheetNum;
     pSupply.IsNew=pIsNew;
     string UserName = SubsonicHelper.GetUserName();
     try
     {
         pSupply.Save(UserName);
     }
     catch(Exception ex)
     {
         LogManager.getInstance().getLogger(typeof(SupplyInfo)).Error(ex);
         if(ex.Message.Contains("插入重复键"))//违反了唯一键
         {
             throw new AppException("此对象已经存在");//此处等待优化可以从唯一约束中直接取出提示来,如果没有的话,默认为原始的出错提示
         }
         throw new AppException("保存失败");
     }
     pSupplyInfo.supplyId = pSupply.SupplyId;
     //如果缓存存在,更新缓存
     if (CachedEntityCommander.IsTypeRegistered(typeof(SupplyInfo)))
     {
         ResetCache();
     }
 }
示例#14
0
        public static DataTable getSupply()
        {
            Query q = Supply.Query();

            return(q.ExecuteDataSet().Tables[0]);
        }
示例#15
0
 public void UpdateSupply(Supply supply)
 {
     _db.Supplies.Update(supply);
     _db.SaveChanges();
 }
示例#16
0
 public GameState GetState(Player p, Supply s)
 {
     return new WorkshopGameState(p, s);
 }
示例#17
0
        internal void SetupSupplies(Game game)
        {
            // Check for addition of Platinum/Colony
            Boolean useColonyPlatinum = false;

            switch (game.Settings.ColonyPlatinumUsage)
            {
            case ColonyPlatinumUsage.Standard:
            case ColonyPlatinumUsage.Used:
            case ColonyPlatinumUsage.NotUsed:
                if (game.RNG.Next(1, _SupplyPiles.Values.Count(s => s.Location == Location.Kingdom) + 1) <=
                    _SupplyPiles.Values.Count(s => s.Location == Location.Kingdom && s.Source == Source.Prosperity))
                {
                    // We have a winner!
                    useColonyPlatinum = true;
                }
                break;

            case ColonyPlatinumUsage.Always:
                useColonyPlatinum = true;
                break;
            }
            if (useColonyPlatinum)
            {
                this.Supplies[Cards.Prosperity.TypeClass.Platinum] = new Supply(game, null, Cards.Prosperity.TypeClass.Platinum, 12);
                this.Supplies[Cards.Prosperity.TypeClass.Colony]   = new Supply(game, null, Cards.Prosperity.TypeClass.Colony, _BaseVictoryCards);
                game.Settings.ColonyPlatinumUsage = ColonyPlatinumUsage.Used;
            }
            else
            {
                game.Settings.ColonyPlatinumUsage = ColonyPlatinumUsage.NotUsed;
            }

            // Check for addition of Shelters
            Boolean useShelter = false;

            switch (game.Settings.ShelterUsage)
            {
            case ShelterUsage.Standard:
            case ShelterUsage.Used:
            case ShelterUsage.NotUsed:
                if (game.RNG.Next(1, _SupplyPiles.Values.Count(s => s.Location == Location.Kingdom) + 1) <=
                    _SupplyPiles.Values.Count(s => s.Location == Location.Kingdom && s.Source == Source.DarkAges))
                {
                    // We have a winner!
                    useShelter = true;
                }
                break;

            case ShelterUsage.Always:
                useShelter = true;
                break;
            }
            if (useShelter)
            {
                this.Estate.Take(3 * game.Players.Count);
                this.Supplies[Cards.DarkAges.TypeClass.Shelters] = new Supply(game, null, Cards.DarkAges.TypeClass.Shelters, Visibility.Top);

                game.Settings.ShelterUsage = ShelterUsage.Used;
            }
            else
            {
                game.Settings.ShelterUsage = ShelterUsage.NotUsed;
            }

            _SupplyPiles.Setup();

            foreach (Supply supply in _SupplyPiles.Values.Concat(SpecialPiles.Values))
            {
                if (supply.CurrentCost.Potion.Value > 0 && !_SupplyPiles.ContainsKey(Cards.Alchemy.TypeClass.Potion))
                {
                    Potion = new Supply(game, game.Players, Cards.Alchemy.TypeClass.Potion, 16);
                    break;
                }

                if (supply.CardTypes.Count() > 1)
                {
                    foreach (Type cardType in supply.CardTypes)
                    {
                        Card card = Card.CreateInstance(cardType);
                        if (game.ComputeCost(card).Potion.Value > 0 && !_SupplyPiles.ContainsKey(Cards.Alchemy.TypeClass.Potion))
                        {
                            Potion = new Supply(game, game.Players, Cards.Alchemy.TypeClass.Potion, 16);
                            break;
                        }
                    }
                }

                if (_SupplyPiles.ContainsKey(Cards.Alchemy.TypeClass.Potion))
                {
                    break;
                }
            }
        }
示例#18
0
 public override Boolean IsEndgameTriggered(Supply supply)
 {
     return(supply.Count == 0);
 }
示例#19
0
 public void Create(Supply item)
 {
     _dataManager.Supplies.Create(item);
 }
示例#20
0
 internal void DeleteSupply(Supply supply)
 {
     // empty ...
 }
示例#21
0
 public bool RemoveSupply(Supply supply)
 {
     return(Supplies.Remove(supply));
 }
示例#22
0
 ///<summary>Inserts one Supply into the database.  Returns the new priKey.  Doesn't use the cache.</summary>
 public static long InsertNoCache(Supply supply)
 {
     return(InsertNoCache(supply, false));
 }
示例#23
0
 ///<summary>Inserts one Supply into the database.  Returns the new priKey.</summary>
 public static long Insert(Supply supply)
 {
     return(Insert(supply, false));
 }
示例#24
0
        private void FillGrid()
        {
            gridMain.BeginUpdate();
            gridMain.Columns.Clear();
            ODGridColumn col = new ODGridColumn(Lan.g(this, "Category"), 130);

            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "Catalog #"), 80);
            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "Supplier"), 100);
            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "Description"), 200);
            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "Price"), 60, HorizontalAlignment.Right);
            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "StockQty"), 60, HorizontalAlignment.Center);
            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "OnHandQty"), 80, HorizontalAlignment.Center);
            gridMain.Columns.Add(col);
            col = new ODGridColumn(Lan.g(this, "IsHidden"), 40, HorizontalAlignment.Center);
            gridMain.Columns.Add(col);
            gridMain.Rows.Clear();
            ODGridRow row;

            for (int i = 0; i < _listSupplies.Count; i++)
            {
                Supply supply = _listSupplies[i];
                if (!checkShowHidden.Checked && supply.IsHidden)
                {
                    continue;                    //If we're filtering out hidden supplies and this one is hidden, skip it.
                }
                if (SelectedSupplierNum != 0 && supply.SupplierNum != SelectedSupplierNum)
                {
                    continue;                    //If we specified a suppliernum outside this form and this supply doesn't have that suppliernum, skip it.
                }
                else if (comboSupplier.SelectedIndex != 0 && _listSuppliers[comboSupplier.SelectedIndex - 1].SupplierNum != supply.SupplierNum)
                {
                    continue;                    //If a supplier is selected in the combo box and this supply doesn't have it, skip it.
                }
                if (checkShowShoppingList.Checked && supply.LevelOnHand >= supply.LevelDesired)
                {
                    continue;                    //If we are only showing those that require restocking and this one has the number desired, skip it.
                }
                if (!string.IsNullOrEmpty(textFind.Text) &&
                    !supply.Descript.ToUpper().Contains(textFind.Text.ToUpper()) &&
                    !supply.CatalogNumber.ToString().ToUpper().Contains(textFind.Text.ToUpper()) &&
                    !Defs.GetName(DefCat.SupplyCats, supply.Category).ToUpper().Contains(textFind.Text.ToUpper()) &&
                    !supply.LevelDesired.ToString().Contains(textFind.Text) &&
                    !supply.Price.ToString().ToUpper().Contains(textFind.Text.ToUpper()) &&
                    !supply.SupplierNum.ToString().Contains(textFind.Text))
                {                //If nothing about the supply matches the text entered in the field, skip it.
                    continue;
                }
                row = new ODGridRow();
                if (gridMain.Rows.Count == 0 || (gridMain.Rows.Count > 0 && supply.Category != ((Supply)gridMain.Rows[gridMain.Rows.Count - 1].Tag).Category))
                {
                    row.Cells.Add(Defs.GetName(DefCat.SupplyCats, supply.Category));                   //Add the new category header in this row if it doesn't match the previous row's category.
                }
                else
                {
                    row.Cells.Add("");
                }
                row.Cells.Add(supply.CatalogNumber);
                row.Cells.Add(Suppliers.GetName(_listSuppliers, supply.SupplierNum));
                row.Cells.Add(supply.Descript);
                if (supply.Price == 0)
                {
                    row.Cells.Add("");
                }
                else
                {
                    row.Cells.Add(supply.Price.ToString("n"));
                }
                if (supply.LevelDesired == 0)
                {
                    row.Cells.Add("");
                }
                else
                {
                    row.Cells.Add(supply.LevelDesired.ToString());
                }
                row.Cells.Add(supply.LevelOnHand.ToString());
                if (supply.IsHidden)
                {
                    row.Cells.Add("X");
                }
                else
                {
                    row.Cells.Add("");
                }
                row.Tag = supply;
                gridMain.Rows.Add(row);
            }
            gridMain.EndUpdate();
            for (int i = 0; i < gridMain.Rows.Count; i++)
            {
                if (_listSelectedSupplies.Contains(((Supply)gridMain.Rows[i].Tag)))
                {
                    gridMain.SetSelected(i, true);
                }
            }
        }
示例#25
0
        /// <summary>
        /// Maps Batch EF object to Batch Model Object and
        /// returns the Batch model object.
        /// </summary>
        /// <param name="result">EF Batch object to be mapped.</param>
        /// <returns>Batch Model Object.</returns>
        public Batch MapEFToModel(EF.Models.Batch data)
        {
            var batch = new Batch()
            {
                BatchId  = data.BatchId,
                Name     = data.Name,
                Quantity = data.Quantity,
                BranchId = data.BranchId,

                BranchName = data.Branch != null ? data.Branch.Name : "",
                SectorName = data.Sector != null ? data.Sector.Name : "",
                SectorId   = data.SectorId,
                CreatedOn  = data.CreatedOn,
                TimeStamp  = data.TimeStamp,
                Deleted    = data.Deleted,
                BranchMillingChargeRate = data.Branch != null? data.Branch.MillingChargeRate:0,
                CreatedBy = _userService.GetUserFullName(data.AspNetUser),
                UpdatedBy = _userService.GetUserFullName(data.AspNetUser1),
            };


            var batchOutPuts = GetAllBatchOutPutsForABatch(data.BatchId);
            List <BatchOutPut> batchOutPutList = new List <BatchOutPut>();

            if (batchOutPuts.Any())
            {
                foreach (var outPut in batchOutPuts)
                {
                    var batchOutPut = new BatchOutPut()
                    {
                        Grades          = outPut.Grades,
                        TotalBuveraCost = outPut.TotalBuveraCost,
                        TotalQuantity   = outPut.TotalQuantity,
                        BrandOutPut     = outPut.BrandOutPut,
                        FlourPercentage = outPut.FlourPercentage,
                        BrandPercentage = outPut.BrandPercentage,
                        FlourOutPut     = outPut.FlourOutPut,
                        LossPercentage  = outPut.LossPercentage,
                        Loss            = outPut.Loss,
                    };
                    batchOutPutList.Add(batchOutPut);
                    batch.TotalBuveraCost = batchOutPut.TotalBuveraCost;
                    batch.TotalQuantity   = batchOutPut.TotalQuantity;
                    batch.FlourOutPut     = batchOutPut.FlourOutPut;
                    batch.LossPercentage  = batchOutPut.LossPercentage;
                    batch.Loss            = Convert.ToDouble(batchOutPut.Loss);
                    batch.BrandOutPut     = batchOutPut.BrandOutPut;
                    batch.BrandPercentage = batchOutPut.BrandPercentage;
                    batch.FlourPercentage = batchOutPut.FlourPercentage;
                    batch.Grades          = batchOutPut.Grades;
                }
            }
            batch.MillingCharge = batch.BranchMillingChargeRate * batch.FlourOutPut;

            var    otherExpenses    = GetAllOtherExpensesForABatch(data.BatchId);
            double otherExpenseCost = 0;
            List <OtherExpense> otherExpenseList = new List <OtherExpense>();

            if (otherExpenses.Any())
            {
                foreach (var other in otherExpenses)
                {
                    var otherExpense = new OtherExpense()
                    {
                        Amount      = other.Amount,
                        Description = other.Description,
                    };
                    otherExpenseList.Add(otherExpense);
                    otherExpenseCost = otherExpenseCost + other.Amount;
                }
                batch.TotalOtherExpenseCost = otherExpenseCost;
                batch.OtherExpenses         = otherExpenseList;
            }

            var            utilities   = GetAllUtilitiesForABatch(data.BatchId);
            double         utilityCost = 0;
            List <Utility> utilityList = new List <Utility>();

            if (utilities.Any())
            {
                foreach (var utility in utilities)
                {
                    var utilityObject = new Utility()
                    {
                        Amount      = utility.Amount,
                        Description = utility.Description,
                    };
                    utilityList.Add(utility);
                    utilityCost = utilityCost + utility.Amount;
                }
                batch.TotalUtilityCost = utilityCost;
                batch.Utilities        = utilityList;
            }

            var    factoryExpenses     = GetAllFactoryExpensesForABatch(data.BatchId);
            double totalFactoryExpense = 0;
            double factoryExpenseCost  = 0;
            List <FactoryExpense> factoryExpenseList = new List <FactoryExpense>();

            if (factoryExpenses.Any())
            {
                foreach (var item in factoryExpenses)
                {
                    var factoryExpense = new FactoryExpense()
                    {
                        Amount      = item.Amount,
                        Description = item.Description,
                    };
                    factoryExpenseList.Add(factoryExpense);
                    factoryExpenseCost = factoryExpenseCost + item.Amount;
                }
                batch.FactoryExpenseCost = factoryExpenseCost;
                batch.FactoryExpenses    = factoryExpenseList;
            }
            var    machineRepairs = GetAllMachineRepairsForABatch(data.BatchId);
            double machineCosts   = 0;
            List <MachineRepair> machineRepairList = new List <MachineRepair>();

            if (machineRepairs.Any())
            {
                foreach (var repair in machineRepairs)
                {
                    var machineRepair = new MachineRepair()
                    {
                        Amount      = repair.Amount,
                        Description = repair.Description,
                    };
                    machineRepairList.Add(machineRepair);
                    machineCosts = machineRepair.Amount + machineCosts;
                }
                batch.MachineRepairs   = machineRepairList;
                batch.TotalMachineCost = machineCosts;
            }
            totalFactoryExpense           = batch.TotalMachineCost + batch.FactoryExpenseCost;
            batch.TotalFactoryExpenseCost = totalFactoryExpense;
            batch.MillingChargeBalance    = ComputeMillingChargeBalance(batch.MillingCharge, batch.TotalFactoryExpenseCost);

            var               labourCosts      = GetAllLabourCostsForABatch(data.BatchId);
            double            totalLabourCosts = 0;
            List <LabourCost> labourCostList   = new List <LabourCost>();

            // labourCostList.AddRange(AddBatchLabourCostsAutomatically(data));
            if (labourCosts.Any())
            {
                foreach (var labour in labourCosts)
                {
                    var labourCost = new LabourCost()
                    {
                        ActivityName = labour.ActivityName,
                        Amount       = labour.Amount,
                        Quantity     = labour.Quantity,
                        Rate         = labour.Rate,
                    };
                    labourCostList.Add(labourCost);
                    totalLabourCosts = totalLabourCosts + labour.Amount;
                }
                batch.TotalLabourCosts = totalLabourCosts;
                batch.LabourCosts      = labourCostList;
            }

            if (data.BatchSupplies != null)
            {
                if (data.BatchSupplies.Any())
                {
                    double        totalSupplyAmount = 0;
                    List <Supply> supplies          = new List <Supply>();
                    var           batchSupplies     = data.BatchSupplies.AsQueryable().Where(m => m.BatchId == data.BatchId);
                    foreach (var batchSupply in batchSupplies)
                    {
                        var supply = new Supply()
                        {
                            SupplyId     = batchSupply.Supply.SupplyId,
                            Quantity     = batchSupply.Supply.Quantity,
                            SupplierId   = batchSupply.Supply.SupplierId,
                            Price        = batchSupply.Supply.Price,
                            Amount       = batchSupply.Supply.Amount,
                            SupplierName = _userService.GetUserFullName(batchSupply.Supply.AspNetUser2),
                        };
                        supplies.Add(supply);
                        totalSupplyAmount = totalSupplyAmount + supply.Amount;
                    }
                    batch.Supplies          = supplies;
                    batch.TotalSupplyAmount = totalSupplyAmount;
                }


                batch.TotalProductionCost = ComputeTotalProductionCost(batch.MillingCharge, batch.TotalLabourCosts, batch.TotalBuveraCost);
            }

            return(batch);
        }
示例#26
0
		public GameBuyMessage(WaitCallback waitCallback, Player player, Supply supply)
			: base(waitCallback)
		{
			Player = player;
			Supply = supply;
		}
 public Task SaveSupplyAsync(Supply supply, bool isNewSupply)
 {
     throw new NotImplementedException();
 }
示例#28
0
 internal static string InsertSupply(Supply supply)
 {
     return(GetCommand(ref insertSupply, insertSupplyPath, new string[] { supply.Product.Product.Id.ToString(), supply.Product.TradePoint.Id.ToString(), supply.Product.Supplier.Id.ToString(), supply.Product.Count.ToString(), supply.Product.Price.ToString(), supply.Order.Id.ToString(), /*supply.Date.ToString("yyyy/mm/dd")*/ "2020/10/10" }));
 }
示例#29
0
        private void OpenEditSupplyWindowMethod(Supply supply)
        {
            EditSupplyWindow editSupplyWindow = new EditSupplyWindow(supply);

            SetCenterPositionAndOpen(editSupplyWindow);
        }
示例#30
0
        public async static System.Threading.Tasks.Task CreateSupplyDocument(int docId, object supplyObj)
        {
            Supply   supply       = (Supply)supplyObj;
            Employee employee     = supply.Employee;
            var      products     = supply.SupplyProducts;
            var      rowsCount    = supply.SupplyProducts.Count;
            var      columnsCount = 6;

            Excel.Application oXL;
            Excel._Workbook   oWB;
            Excel._Worksheet  oSheet;
            object            oMissing = System.Reflection.Missing.Value;

            try
            {
                API            api            = API.GetInstance();
                CompanyDetails companyDetails = await api.GetCompanyDetails();

                List <Unit> units = await api.AsyncGetCatalog <Unit>();

                oXL         = new Excel.Application();
                oXL.Visible = true;

                //Get a new workbook.
                string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                string resourceFolder   = Path.Combine(currentDirectory, "Resources");
                string file             = Path.Combine(resourceFolder, "supplyDoc.xls");
                oWB    = (Excel._Workbook)(oXL.Workbooks.Add(file));
                oSheet = (Excel._Worksheet)oWB.ActiveSheet;

                oSheet.get_Range("D2", "I2").Value2 = companyDetails.Name;
                oSheet.get_Range("D3", "F3").Value2 = companyDetails.INN;
                oSheet.get_Range("H4").Value2       = docId;
                oSheet.get_Range("F5", "G5").Value2 = DateTime.Now.ToShortDateString();
                oSheet.get_Range("E15").Value2      = $"{employee}";
                for (int i = 1; i < rowsCount; i++)
                {
                    oSheet.get_Range("B10:I10").EntireRow.Insert(oMissing, XlInsertFormatOrigin.xlFormatFromRightOrBelow);
                }
                for (int i = 0; i < rowsCount; i++)
                {
                    var range = (Excel.Range)oSheet.Range[oSheet.Cells[10 + i, 3], oSheet.Cells[10 + i, 5]];
                    range.Merge();
                }
                var tableRange = (Excel.Range)oSheet.Range[oSheet.Cells[10, 2], oSheet.Cells[10, 9]];
                tableRange = tableRange.get_Resize(rowsCount, columnsCount);

                for (int row = 10, i; row < 10 + rowsCount; row++)
                {
                    i = row - 10;
                    oSheet.Cells[row, 2].Value2 = (i + 1);
                    oSheet.Cells[row, 3].Value2 = products[i].Product.ToString();
                    oSheet.Cells[row, 6].Value2 = units
                                                  .Where(u => u.Id == products[i].Product.UnitId)
                                                  .FirstOrDefault()
                                                  .ToString();
                    oSheet.Cells[row, 7].Value2 = products[i].Product.Price;
                    oSheet.Cells[row, 8].Value2 = products[i].Quantity;
                    oSheet.Cells[row, 9].Value2 = (products[i].Product.Price * (decimal)products[i].Quantity);
                }
                decimal sum = products.Sum(p => (decimal)p.Quantity * p.Product.Price);
                oSheet.Cells[10 + rowsCount, 9].Value2 = sum;

                INumberToWordConverter numberToWordsConverter = NumbersToWordsConverterFactory.CreateRussianConverter();
                string convertResult = numberToWordsConverter.ConvertCurrency(sum);
                oSheet.Cells[10 + rowsCount + 2, 2].Value2 = convertResult;

                //Make sure Excel is visible and give the user control
                //of Microsoft Excel's lifetime.
                oXL.Visible     = true;
                oXL.UserControl = true;
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#31
0
 public WorkshopGameState(Player p, Supply s)
 {
     player = p;
     supply = s;
 }
示例#32
0
        public long SaveSupply(Supply supply, string userId)
        {
            double amount = 0, totalBags = 0, offloadingFee = 0, amountToPay = 0;

            amount = (supply.Price * supply.Quantity);

            var supplies = GetAllSuppliesForAParticularSupplier(supply.SupplierId);

            if (supplies.Any())
            {
                foreach (var supplierSupply in supplies)
                {
                    bool equals = supplierSupply.WeightNoteNumber.Equals(supply.WeightNoteNumber, StringComparison.OrdinalIgnoreCase);

                    if (equals)
                    {
                        return(-1);
                    }
                }
            }

            if (supply.Offloading == "NO")
            {
                totalBags     = supply.NormalBags + supply.BagsOfStones;
                offloadingFee = totalBags * (Convert.ToDouble(offloadingRate));
                amountToPay   = amount - offloadingFee;
            }
            else
            {
                amountToPay = amount;
            }
            var supplyDTO = new DTO.SupplyDTO()
            {
                Quantity   = supply.Quantity,
                SupplyDate = supply.SupplyDate,
                //SupplyNumber = supply.SupplyNumber,
                BranchId         = supply.BranchId,
                SupplierId       = supply.SupplierId,
                Amount           = amount,
                TruckNumber      = supply.TruckNumber,
                AmountToPay      = amountToPay,
                Used             = supply.Used,
                SupplyId         = supply.SupplyId,
                WeightNoteNumber = supply.WeightNoteNumber,
                MoistureContent  = supply.MoistureContent,
                NormalBags       = supply.NormalBags,
                BagsOfStones     = supply.BagsOfStones,
                Price            = supply.Price,
                IsPaid           = supply.IsPaid,
                StatusId         = supply.StatusId,
                CreatedOn        = supply.CreatedOn,
                TimeStamp        = supply.TimeStamp,
                CreatedBy        = supply.CreatedBy,
                Deleted          = supply.Deleted,
                StoreId          = supply.StoreId,
                Offloading       = supply.Offloading,
            };

            var supplyId = this._dataService.SaveSupply(supplyDTO, userId);

            var storeMaizeStock = new StoreMaizeStock()
            {
                SupplyId = supplyId,
                Quantity = supply.Quantity,
                StoreId  = supply.StoreId,
                BranchId = supply.BranchId,
                SectorId = Convert.ToInt64(sectorId),
            };

            SaveStoreMaizeStock(storeMaizeStock, true);
            var notes           = "Maize supply";
            var accountActivity = new AccountTransactionActivity()
            {
                AspNetUserId = supply.SupplierId,

                Amount               = amount,
                Notes                = notes,
                Action               = "+",
                BranchId             = supply.BranchId,
                TransactionSubTypeId = Convert.ToInt64(supplyTransactionSubTypeId),
                SectorId             = Convert.ToInt64(sectorId),
                Deleted              = supply.Deleted,
                CreatedBy            = userId,
                SupplyId             = supplyId,
            };
            var accountActivityId = this._accountTransactionActivityService.SaveAccountTransactionActivity(accountActivity, userId);



            var offLoadingNotes           = "Offloading fee";
            var accountActivityOffloading = new AccountTransactionActivity()
            {
                AspNetUserId = supply.SupplierId,

                Amount               = offloadingFee,
                Notes                = offLoadingNotes,
                Action               = "-",
                BranchId             = supply.BranchId,
                TransactionSubTypeId = Convert.ToInt64(offLoadingTransactionSubTypeId),
                SectorId             = Convert.ToInt64(sectorId),
                Deleted              = supply.Deleted,
                CreatedBy            = userId,
                SupplyId             = supplyId,
            };
            var accountActivityOffloadingId = this._accountTransactionActivityService.SaveAccountTransactionActivity(accountActivityOffloading, userId);



            return(supplyId);
        }
        /// <summary>
        /// Saves a new Supply or updates an already existing Supply.
        /// </summary>
        /// <param name="Supply">Supply to be saved or updated.</param>
        /// <param name="SupplyId">SupplyId of the Supply creating or updating</param>
        /// <returns>SupplyId</returns>
        public long SaveSupply(SupplyDTO supplyDTO, string userId)
        {
            long supplyId = 0;

            if (supplyDTO.SupplyId == 0)
            {
                var supply = new Supply()
                {
                    Quantity   = supplyDTO.Quantity,
                    SupplyDate = supplyDTO.SupplyDate,
                    //SupplyNumber = supplyDTO.SupplyNumber,
                    BranchId         = supplyDTO.BranchId,
                    SupplierId       = supplyDTO.SupplierId,
                    Amount           = supplyDTO.Amount,
                    TruckNumber      = supplyDTO.TruckNumber,
                    Used             = supplyDTO.Used,
                    MoistureContent  = supplyDTO.MoistureContent,
                    WeightNoteNumber = supplyDTO.WeightNoteNumber,
                    NormalBags       = supplyDTO.NormalBags,
                    BagsOfStones     = supplyDTO.BagsOfStones,
                    Price            = supplyDTO.Price,
                    IsPaid           = supplyDTO.IsPaid,
                    StatusId         = Convert.ToInt64(supplyStatusId),
                    CreatedOn        = DateTime.Now,
                    TimeStamp        = DateTime.Now,
                    CreatedBy        = userId,
                    Deleted          = false,
                    AmountToPay      = supplyDTO.AmountToPay,
                    StoreId          = supplyDTO.StoreId,
                    Offloading       = supplyDTO.Offloading,
                };

                this.UnitOfWork.Get <Supply>().AddNew(supply);
                this.UnitOfWork.SaveChanges();
                supplyId = supply.SupplyId;
                return(supplyId);
            }

            else
            {
                var result = this.UnitOfWork.Get <Supply>().AsQueryable()
                             .SingleOrDefault(e => e.SupplyId == supplyDTO.SupplyId);
                if (result != null)
                {
                    result.Quantity   = supplyDTO.Quantity;
                    result.SupplyDate = supplyDTO.SupplyDate;
                    //result.SupplyNumber =  supplyDTO.SupplyNumber;
                    result.BranchId         = supplyDTO.BranchId;
                    result.SupplierId       = supplyDTO.SupplierId;
                    result.Amount           = supplyDTO.Amount;
                    result.IsPaid           = supplyDTO.IsPaid;
                    result.TruckNumber      = supplyDTO.TruckNumber;
                    result.Price            = supplyDTO.Price;
                    result.AmountToPay      = supplyDTO.AmountToPay;
                    result.Used             = supplyDTO.Used;
                    result.WeightNoteNumber = supplyDTO.WeightNoteNumber;
                    result.BagsOfStones     = supplyDTO.BagsOfStones;
                    result.NormalBags       = supplyDTO.NormalBags;
                    result.StatusId         = supplyDTO.StatusId;
                    result.MoistureContent  = supplyDTO.MoistureContent;
                    result.UpdatedBy        = userId;
                    result.TimeStamp        = DateTime.Now;
                    result.Deleted          = supplyDTO.Deleted;
                    result.DeletedBy        = supplyDTO.DeletedBy;
                    result.DeletedOn        = supplyDTO.DeletedOn;
                    result.StoreId          = supplyDTO.StoreId;
                    result.Offloading       = supplyDTO.Offloading;

                    this.UnitOfWork.Get <Supply>().Update(result);

                    this.UnitOfWork.SaveChanges();
                }
                return(supplyDTO.SupplyId);
            }
        }
示例#34
0
		public override void Setup(Game game, Supply supply)
		{
			base.Setup(game, supply);

			IList<Card> availableCards = null; 
			try
			{
				if (game.Settings.Preset != null)
				{
					availableCards = game.Settings.Preset.CardCards[game.Settings.Preset.Cards.First(c => c.CardType == typeof(BlackMarket))];
					// Shuffle the preset cards -- these should definitely not be set up in a known order
					Utilities.Shuffler.Shuffle(availableCards);
				}
				else
				{
					int cardsToUse = 25;
					//Boolean errorOnNotEnoughCards = true;
					Boolean shouldUseGameConstraints = true;
					ConstraintCollection bmConstraints = new ConstraintCollection();
					if (game.Settings.CardSettings.ContainsKey("Black Market"))
					{
						CardsSettings bmSettings = game.Settings.CardSettings["Black Market"];
						cardsToUse = (int)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_NumberOfCards)].Value;
						//errorOnNotEnoughCards = (Boolean)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_ErrorOnNotEnoughCards)].Value;
						shouldUseGameConstraints = (Boolean)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_UseGameConstraints)].Value;
						bmConstraints = (ConstraintCollection)bmSettings.CardSettingCollection[typeof(BlackMarket.BlackMarket_Constraints)].Value;
					}

					// need to set up a supply pile for Black Market; randomly pick an unused supply card and add it to the pile until we have the requisite number of cards
					availableCards = game.CardsAvailable;
					if (shouldUseGameConstraints)
					{
						// Skip all "Must Use" constraints
						ConstraintCollection constraints = new ConstraintCollection(game.Settings.Constraints.Where(c => c.ConstraintType != ConstraintType.CardMustUse));
						availableCards = constraints.SelectCards(availableCards, cardsToUse);
					}
					else
						availableCards = bmConstraints.SelectCards(availableCards, cardsToUse);
				}
			}
			catch (DominionBase.Cards.ConstraintException ce)
			{
				throw new BlackMarketConstraintException(String.Format("Problem setting up Black Market constraints: {0}", ce.Message));
			}

			foreach (Card cardToUse in availableCards)
			{
				game.CardsAvailable.Remove(cardToUse);
				supply.AddTo(cardToUse);
			}
		}
示例#35
0
 public void AddSupply(Supply supply)
 {
     _db.Supplies.Add(supply);
     _db.SaveChanges();
 }
示例#36
0
文件: SupplyDao.cs 项目: ldd-soft/scm
 public int Create(Supply supply)
 {
     db.Supply.InsertOnSubmit(supply);
     db.SubmitChanges();
     return(supply.Id);
 }
 public ActionResult Create(Supply supply)
 {
     context.Supplies.Add(supply);
     context.SaveChanges();
     return(RedirectToAction("Index"));
 }
示例#38
0
 private void buttonSuppliesAfterDate_Click(object sender, EventArgs e)
 {
     Supply.GetSuppliesAfterDate(sqlConnection, sqlDataAdapter, checkBoxFillingRightTable.Checked ? dataGridViewSecondTable : dataGridViewFirstTable, dateTimePickerSupplySpecifyDate.Value.ToString().Substring(0, 10));
 }
示例#39
0
 //从后台获取数据
 internal static void LoadFromDAL(SupplyInfo pSupplyInfo, Supply  pSupply)
 {
     pSupplyInfo.supplyId = pSupply.SupplyId;
      		pSupplyInfo.supplyName = pSupply.SupplyName;
      		pSupplyInfo.sheetNum = pSupply.SheetNum;
     pSupplyInfo.Loaded=true;
 }
示例#40
0
 private void buttonSuppliesWithManagers_Click(object sender, EventArgs e)
 {
     Supply.GetSuppliesWithManagers(sqlConnection, sqlDataAdapter, checkBoxFillingRightTable.Checked ? dataGridViewSecondTable : dataGridViewFirstTable);
 }
示例#41
0
 private void LoadFromId(int supplyId)
 {
     if (CachedEntityCommander.IsTypeRegistered(typeof(SupplyInfo)))
     {
         SupplyInfo supplyInfo=Find(GetList(), supplyId);
         if(supplyInfo==null)
             throw new AppException("未能在缓存中找到相应的键值对象");
         Copy(supplyInfo, this);
     }
     else
     {	Supply supply=new Supply( supplyId);
         if(supply.IsNew)
         throw new AppException("尚未初始化");
        	LoadFromDAL(this, supply);
     }
 }
示例#42
0
		/// <summary>
		/// Tries to gain from the specified supply
		/// </summary>
		/// <param name="supply">The supply pile to gain from</param>
		/// <param name="isBought">Indicating whether or not the card was bought</param>
		/// <returns>True if the card was actually gained, False otherwise</returns>
		public Boolean Gain(Supply supply, Boolean isBought)
		{
			return this.Gain(supply, supply.TopCard == null ? null : supply.TopCard.CardType, DeckLocation.Discard, DeckPosition.Automatic, isBought);
		}
示例#43
0
        ///<summary>Updates one Supply in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.  Returns true if an update occurred.</summary>
        public static bool Update(Supply supply, Supply oldSupply)
        {
            string command = "";

            if (supply.SupplierNum != oldSupply.SupplierNum)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "SupplierNum = " + POut.Long(supply.SupplierNum) + "";
            }
            if (supply.CatalogNumber != oldSupply.CatalogNumber)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "CatalogNumber = '" + POut.String(supply.CatalogNumber) + "'";
            }
            if (supply.Descript != oldSupply.Descript)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Descript = '" + POut.String(supply.Descript) + "'";
            }
            if (supply.Category != oldSupply.Category)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Category = " + POut.Long(supply.Category) + "";
            }
            if (supply.ItemOrder != oldSupply.ItemOrder)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ItemOrder = " + POut.Int(supply.ItemOrder) + "";
            }
            if (supply.LevelDesired != oldSupply.LevelDesired)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "LevelDesired = " + POut.Float(supply.LevelDesired) + "";
            }
            if (supply.IsHidden != oldSupply.IsHidden)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "IsHidden = " + POut.Bool(supply.IsHidden) + "";
            }
            if (supply.Price != oldSupply.Price)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Price = '" + POut.Double(supply.Price) + "'";
            }
            if (supply.BarCodeOrID != oldSupply.BarCodeOrID)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "BarCodeOrID = '" + POut.String(supply.BarCodeOrID) + "'";
            }
            if (supply.DispDefaultQuant != oldSupply.DispDefaultQuant)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "DispDefaultQuant = " + POut.Float(supply.DispDefaultQuant) + "";
            }
            if (supply.DispUnitsCount != oldSupply.DispUnitsCount)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "DispUnitsCount = " + POut.Int(supply.DispUnitsCount) + "";
            }
            if (supply.DispUnitDesc != oldSupply.DispUnitDesc)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "DispUnitDesc = '" + POut.String(supply.DispUnitDesc) + "'";
            }
            if (supply.LevelOnHand != oldSupply.LevelOnHand)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "LevelOnHand = " + POut.Float(supply.LevelOnHand) + "";
            }
            if (command == "")
            {
                return(false);
            }
            command = "UPDATE supply SET " + command
                      + " WHERE SupplyNum = " + POut.Long(supply.SupplyNum);
            Db.NonQ(command);
            return(true);
        }
示例#44
0
		/// <summary>
		/// Tries to gain the number of cards specified from the specified supply into the location and position of the deck specified
		/// </summary>
		/// <param name="supply">The supply pile to gain from</param>
		/// <param name="location">The deck the card should go into</param>
		/// <param name="position">The position into the deck the card should go</param>
		/// <param name="count">How many cards to gain</param>
		/// <returns>True if the card was actually gained, False otherwise</returns>
		public Boolean Gain(Supply supply, DeckLocation location, DeckPosition position, int count)
		{
			Boolean success = true;
			for (int i = 0; i < count; i++)
				success &= this.Gain(supply, supply.TopCard == null ? null : supply.TopCard.CardType, location, position, false);
			return success;
		}
示例#45
0
        ///<summary>Updates one Supply in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
        public static void Update(Supply supply, Supply oldSupply)
        {
            string command = "";

            if (supply.SupplierNum != oldSupply.SupplierNum)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "SupplierNum = " + POut.Long(supply.SupplierNum) + "";
            }
            if (supply.CatalogNumber != oldSupply.CatalogNumber)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "CatalogNumber = '" + POut.String(supply.CatalogNumber) + "'";
            }
            if (supply.Descript != oldSupply.Descript)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Descript = '" + POut.String(supply.Descript) + "'";
            }
            if (supply.Category != oldSupply.Category)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Category = " + POut.Long(supply.Category) + "";
            }
            if (supply.ItemOrder != oldSupply.ItemOrder)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ItemOrder = " + POut.Int(supply.ItemOrder) + "";
            }
            if (supply.LevelDesired != oldSupply.LevelDesired)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "LevelDesired = " + POut.Float(supply.LevelDesired) + "";
            }
            if (supply.IsHidden != oldSupply.IsHidden)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "IsHidden = " + POut.Bool(supply.IsHidden) + "";
            }
            if (supply.Price != oldSupply.Price)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Price = '" + POut.Double(supply.Price) + "'";
            }
            if (command == "")
            {
                return;
            }
            command = "UPDATE supply SET " + command
                      + " WHERE SupplyNum = " + POut.Long(supply.SupplyNum);
            Db.NonQ(command);
        }
示例#46
0
		/// <summary>
		/// Tries to gain the specified cardType from the specified supply into the location and position of the deck specified
		/// </summary>
		/// <param name="supply">The supply pile to gain from</param>
		/// <param name="cardType">The card type we're trying to gain</param>
		/// <param name="location">The deck the card should go into</param>
		/// <param name="position">The position into the deck the card should go</param>
		/// <param name="isBought">Indicating whether or not the card was bought</param>
		/// <returns>True if the card was actually gained, False otherwise</returns>
		public Boolean Gain(Supply supply, Type cardType, DeckLocation location, DeckPosition position, Boolean isBought)
		{
			if (supply.CanGain(cardType))
			{
				Card supplyCard = supply[cardType].First();
				CardGainEventArgs cgea = CardGainCheckAllowed(supplyCard, location, position, isBought);
				if (!cgea.Cancelled)
					return this.Gain(supply.Take(cardType), cgea.Location, cgea.Position, cgea.Bought);
				else
				{
					CardGainFinish(supplyCard, cgea.Location, cgea.Position, cgea.Bought, cgea.Cancelled, cgea.IsLostTrackOf);
					return false;
				}
			}
			return false;
		}
示例#47
0
 public void Update(Supply item)
 {
     _dataManager.Supplies.Update(item);
 }
        private async void ExecuteSaveAsync()
        {
            if (NewSupply.Future == true && NewSupplyFuture.Place == null)
            {
                await _currentWindow.ShowMessageAsync("فشل الإضافة", "يجب كتابة مكان الدفع", MessageDialogStyle.Affirmative, new MetroDialogSettings()
                {
                    AffirmativeButtonText = "موافق",
                    DialogMessageFontSize = 25,
                    DialogTitleFontSize   = 30
                });

                return;
            }
            Mouse.OverrideCursor = Cursors.Wait;
            DateTime _dt = DateTime.Now;

            _newSupply.RegistrationDate = _dt;
            _supplyServ.AddSupply(_newSupply);
            int _supplyID = _supplyServ.GetLastSupplyID();

            foreach (var item in _supplyCategories)
            {
                SupplyCategory _supplyCategory = new SupplyCategory
                {
                    CategoryID             = item.CategoryID,
                    Cost                   = item.Cost,
                    CostAfterDiscount      = item.CostAfterDiscount,
                    CostAfterTax           = item.CostAfterTax,
                    CostTotal              = item.CostTotal,
                    CostTotalAfterDiscount = item.CostTotalAfterDiscount,
                    CostTotalAfterTax      = item.CostTotalAfterTax,
                    Discount               = item.Discount,
                    DiscountValue          = item.DiscountValue,
                    DiscountValueTotal     = item.DiscountValueTotal,
                    SupplyID               = _supplyID,
                    Qty           = item.Qty,
                    Tax           = item.Tax,
                    TaxValue      = item.TaxValue,
                    TaxValueTotal = item.TaxValueTotal,
                    Price         = item.Price
                };
                _supplyCategoryServ.AddSupplyCategory(_supplyCategory);

                Category cat = _categoryServ.GetCategory(item.CategoryID);
                if (cat.Qty + item.Qty != 0)
                {
                    cat.Cost = (item.CostTotalAfterDiscount + (cat.Cost * cat.Qty)) / (cat.Qty + item.Qty);
                }
                cat.Qty   = cat.Qty + item.Qty;
                cat.Price = item.Price;
                _categoryServ.UpdateCategory(cat);
            }

            if (_newSupply.Future == true)
            {
                _newSupplyFuture.Change   = _newSupply.Change;
                _newSupplyFuture.SupplyID = _supplyID;
                if (_newSupplyFuture.Cheque == false)
                {
                    _newSupplyFuture.ChequeNumber = null;
                }
                _supplyFutureServ.AddSupplyFuture(_newSupplyFuture);
                _placesSuggestions.Add(_newSupplyFuture.Place);
            }
            ClientAccount _account = new ClientAccount
            {
                ClientID         = _newSupply.ClientID,
                Date             = _newSupply.Date,
                RegistrationDate = _dt,
                Statement        = "فاتورة مشتريات رقم " + _supplyID,
                Credit           = _newSupply.CostAfterTax,
                Debit            = _newSupply.CashPaid
            };

            _clientAccountServ.AddAccount(_account);
            if (_newSupply.DiscountPaid != 0 || _newSupply.TotalDiscount != 0)
            {
                _account = new ClientAccount
                {
                    ClientID         = _newSupply.ClientID,
                    Date             = _newSupply.Date,
                    RegistrationDate = _dt,
                    Statement        = "خصومات فاتورة مشتريات رقم " + _supplyID,
                    Credit           = _newSupply.DiscountPaid,
                    Debit            = _newSupply.TotalDiscount
                };
                _clientAccountServ.AddAccount(_account);
            }
            if (_newSupply.CashPaid > 0)
            {
                Safe _safe = new Safe
                {
                    Date             = _newSupply.Date,
                    RegistrationDate = _dt,
                    Statement        = "فاتورة مشتريات رقم " + _supplyID + " من العميل : " + _selectedClient.Name,
                    Amount           = -_newSupply.CashPaid,
                    Source           = 3
                };
                _safeServ.AddSafe(_safe);
            }

            DS ds = new DS();

            ds.Sale.Rows.Clear();
            int i = 0;

            foreach (var item in _supplyCategories)
            {
                ds.Sale.Rows.Add();
                ds.Sale[i]["ID"]         = _supplyID;
                ds.Sale[i]["Date"]       = _newSupply.Date;
                ds.Sale[i]["Client"]     = _selectedClient.Name;
                ds.Sale[i]["Serial"]     = i + 1;
                ds.Sale[i]["Category"]   = item.Category + " " + item.Company;
                ds.Sale[i]["Qty"]        = item.Qty;
                ds.Sale[i]["Price"]      = Math.Round(Convert.ToDecimal(item.CostAfterTax), 2);
                ds.Sale[i]["TotalPrice"] = Math.Round(Convert.ToDecimal(item.CostTotalAfterTax), 2);
                ds.Sale[i]["BillPrice"]  = Math.Round(Convert.ToDecimal(_newSupply.CostAfterTax), 2);
                ds.Sale[i]["OldDebt"]    = Math.Abs(Math.Round(Convert.ToDecimal(_newSupply.OldDebt), 2));

                ds.Sale[i]["Paid"]    = Math.Abs(Math.Round(Convert.ToDecimal(_newSupply.CashPaid + _newSupply.DiscountPaid), 2));
                ds.Sale[i]["NewDebt"] = Math.Abs(Math.Round(Convert.ToDecimal(_newSupply.NewDebt), 2));
                if (_newSupply.NewDebt > 0)
                {
                    ds.Sale[i]["PrintingMan"] = "له";
                }
                else if (_newSupply.NewDebt < 0)
                {
                    ds.Sale[i]["PrintingMan"] = "عليه";
                }

                if (_newSupply.OldDebt > 0)
                {
                    ds.Sale[i]["Type"] = "له";
                }
                else if (_newSupply.OldDebt < 0)
                {
                    ds.Sale[i]["Type"] = "عليه";
                }
                ds.Sale[i]["BillTotal"] = Math.Abs(Math.Round(Convert.ToDecimal(_newSupply.OldDebt), 2) + Math.Round(Convert.ToDecimal(_newSupply.CostAfterTax), 2));
                if (Math.Round(Convert.ToDecimal(_newSupply.OldDebt), 2) + Math.Round(Convert.ToDecimal(_newSupply.CostAfterTax), 2) > 0)
                {
                    ds.Sale[i]["Type2"] = "له";
                }
                else if (Math.Round(Convert.ToDecimal(_newSupply.OldDebt), 2) + Math.Round(Convert.ToDecimal(_newSupply.CostAfterTax), 2) < 0)
                {
                    ds.Sale[i]["Type2"] = "عليه";
                }
                i++;
            }
            ReportWindow rpt       = new ReportWindow();
            SupplyReport supplyRPT = new SupplyReport();

            supplyRPT.SetDataSource(ds.Tables["Sale"]);
            rpt.crv.ViewerCore.ReportSource = supplyRPT;
            Mouse.OverrideCursor            = null;
            _currentWindow.Hide();
            rpt.ShowDialog();

            NewSupply            = new Supply();
            NewSupplyCategory    = new SupplyCategoryVM();
            NewSupplyFuture      = new SupplyFuture();
            SupplyCategories     = new ObservableCollection <SupplyCategoryVM>();
            NewSupply.Date       = DateTime.Now;
            NewSupplyFuture.Date = DateTime.Now;
            OldCosts             = new ObservableCollection <SupplyCategory>();
            _currentWindow.ShowDialog();
        }
示例#49
0
 public void Play(Player p, Supply s)
 {
     p.NumBuys += 1;
 }
示例#50
0
 ///<summary>Updates one Supply in the database.</summary>
 internal static void Update(Supply supply)
 {
     string command="UPDATE supply SET "
         +"SupplierNum  =  "+POut.Long  (supply.SupplierNum)+", "
         +"CatalogNumber= '"+POut.String(supply.CatalogNumber)+"', "
         +"Descript     = '"+POut.String(supply.Descript)+"', "
         +"Category     =  "+POut.Long  (supply.Category)+", "
         +"ItemOrder    =  "+POut.Int   (supply.ItemOrder)+", "
         +"LevelDesired =  "+POut.Float (supply.LevelDesired)+", "
         +"IsHidden     =  "+POut.Bool  (supply.IsHidden)+", "
         +"Price        = '"+POut.Double(supply.Price)+"' "
         +"WHERE SupplyNum = "+POut.Long(supply.SupplyNum);
     Db.NonQ(command);
 }
示例#51
0
 public void Play(Player p, Supply s)
 {
 }
示例#52
0
 ///<summary>Updates one Supply in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
 internal static void Update(Supply supply,Supply oldSupply)
 {
     string command="";
     if(supply.SupplierNum != oldSupply.SupplierNum) {
         if(command!=""){ command+=",";}
         command+="SupplierNum = "+POut.Long(supply.SupplierNum)+"";
     }
     if(supply.CatalogNumber != oldSupply.CatalogNumber) {
         if(command!=""){ command+=",";}
         command+="CatalogNumber = '"+POut.String(supply.CatalogNumber)+"'";
     }
     if(supply.Descript != oldSupply.Descript) {
         if(command!=""){ command+=",";}
         command+="Descript = '"+POut.String(supply.Descript)+"'";
     }
     if(supply.Category != oldSupply.Category) {
         if(command!=""){ command+=",";}
         command+="Category = "+POut.Long(supply.Category)+"";
     }
     if(supply.ItemOrder != oldSupply.ItemOrder) {
         if(command!=""){ command+=",";}
         command+="ItemOrder = "+POut.Int(supply.ItemOrder)+"";
     }
     if(supply.LevelDesired != oldSupply.LevelDesired) {
         if(command!=""){ command+=",";}
         command+="LevelDesired = "+POut.Float(supply.LevelDesired)+"";
     }
     if(supply.IsHidden != oldSupply.IsHidden) {
         if(command!=""){ command+=",";}
         command+="IsHidden = "+POut.Bool(supply.IsHidden)+"";
     }
     if(supply.Price != oldSupply.Price) {
         if(command!=""){ command+=",";}
         command+="Price = '"+POut.Double(supply.Price)+"'";
     }
     if(command==""){
         return;
     }
     command="UPDATE supply SET "+command
         +" WHERE SupplyNum = "+POut.Long(supply.SupplyNum);
     Db.NonQ(command);
 }
示例#53
0
        private void ExecuteSave()
        {
            try
            {
                DateTime _dt = DateTime.Now;
                _newSupply.RegistrationDate = _dt;
                _supplyServ.AddSupply(_newSupply);
                int _supplyID = _supplyServ.GetLastSupplyID();

                foreach (var item in _supplyCategories)
                {
                    SupplyCategory _supplyCategory = new SupplyCategory
                    {
                        CategoryID = item.CategoryID,
                        Cost       = item.Cost,
                        CostTotal  = item.CostTotal,
                        SupplyID   = _supplyID,
                        Qty        = item.Qty,
                        Price      = item.Price
                    };
                    _supplyCategoryServ.AddSupplyCategory(_supplyCategory);

                    Category cat = _categoryServ.GetCategory(item.CategoryID);
                    if (cat.Qty + item.Qty != 0)
                    {
                        cat.Cost = (item.CostTotal + (cat.Cost * cat.Qty)) / (cat.Qty + item.Qty);
                    }
                    cat.Qty   = cat.Qty + item.Qty;
                    cat.Price = item.Price;
                    _categoryServ.UpdateCategory(cat);
                }
                ClientAccount _account = new ClientAccount
                {
                    ClientID         = _newSupply.ClientID,
                    Date             = _newSupply.Date,
                    RegistrationDate = _dt,
                    Statement        = "فاتورة مشتريات رقم " + _supplyID,
                    Credit           = _newSupply.Cost,
                    Debit            = _newSupply.CashPaid + _newSupply.DiscountPaid
                };
                _clientAccountServ.AddAccount(_account);

                if (_newSupply.CashPaid > 0)
                {
                    Safe _safe = new Safe
                    {
                        Date             = _newSupply.Date,
                        RegistrationDate = _dt,
                        Statement        = "فاتورة مشتريات رقم " + _supplyID + " من العميل : " + _selectedClient.Name,
                        Amount           = -_newSupply.CashPaid,
                        Source           = 3
                    };
                    _safeServ.AddSafe(_safe);
                }
                NewSupply         = new Supply();
                NewSupplyCategory = new SupplyCategoryVM();
                SupplyCategories  = new ObservableCollection <SupplyCategoryVM>();
                NewSupply.Date    = DateTime.Now;
                OldCosts          = new ObservableCollection <SupplyCategory>();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
示例#54
0
        public void GenerateData(DataContext data)
        {
            Customer customer1 = new Customer()
            {
                Id        = 1,
                FirstName = "Matt",
                LastName  = "Newman"
            };
            Customer customer2 = new Customer()
            {
                Id        = 2,
                FirstName = "John",
                LastName  = "Watts"
            };

            data.Customers.Add(customer1);
            data.Customers.Add(customer2);

            Product product1 = new Product()
            {
                Id    = 1,
                Name  = "Sofa",
                Price = 243.23
            };
            Product product2 = new Product()
            {
                Id    = 2,
                Name  = "Table",
                Price = 99.99
            };

            data.Products.Add(product1);
            data.Products.Add(product2);

            data.ProductAmount.Add(product1, 10);
            data.ProductAmount.Add(product2, 20);

            Sale sale1 = new Sale()
            {
                Id            = 1,
                Date          = DateTime.Today,
                ProductId     = 1,
                ProductAmount = 1,
                CustomerId    = 1
            };
            Sale sale2 = new Sale()
            {
                Id            = 2,
                Date          = DateTime.Today,
                ProductId     = 2,
                ProductAmount = 3,
                CustomerId    = 2
            };

            data.Sales.Add(sale1);
            data.Sales.Add(sale2);

            Supply supply1 = new Supply()
            {
                Id            = 1,
                Date          = DateTime.Today,
                ProductId     = 1,
                ProductAmount = 1
            };
            Supply supply2 = new Supply()
            {
                Id            = 2,
                Date          = DateTime.Today,
                ProductId     = 2,
                ProductAmount = 2
            };

            data.Supplies.Add(supply1);
            data.Supplies.Add(supply2);
        }
示例#55
0
		/// <summary>
		/// Tries to gain from the specified supply into the location and position of the deck specified
		/// </summary>
		/// <param name="supply">The supply pile to gain from</param>
		/// <param name="location">The deck the card should go into</param>
		/// <param name="position">The position into the deck the card should go</param>
		/// <returns>True if the card was actually gained, False otherwise</returns>
		public Boolean Gain(Supply supply, DeckLocation location, DeckPosition position)
		{
			return Gain(supply, supply.TopCard == null ? null : supply.TopCard.CardType, location, position, false);
		}
示例#56
0
        public static bool GetSupplyOrComponentAmbiguous(string supplyNoOrComponentName, out DataAccess.Component component, out Supply supply, out string errorMessage, int supplierID = -1, WMSEntities wmsEntities = null)
        {
            if (wmsEntities == null)
            {
                wmsEntities = new WMSEntities();
            }
            //如果输入的名字是空的,直接抛出异常。这儿不允许传入空的
            if (string.IsNullOrWhiteSpace(supplyNoOrComponentName))
            {
                throw new Exception("GetSupplyOrComponent()函数不允许传入空的零件名字(代号)!空格也不行!请使用string.IsNullOrWhiteSpace()自行判空");
            }
            //首先精确查询,如果没有,再模糊查询
            component = (from c in wmsEntities.Component
                         where c.Name == supplyNoOrComponentName &&
                         (from s in wmsEntities.Supply
                          where s.ComponentID == c.ID &&
                          s.ProjectID == GlobalData.ProjectID &&
                          s.WarehouseID == GlobalData.WarehouseID &&
                          s.SupplierID == (supplierID == -1 ? s.SupplierID : supplierID)
                          select s).Count() > 0
                         select c).FirstOrDefault();
            supply = (from s in wmsEntities.Supply
                      where s.No == supplyNoOrComponentName &&
                      s.ProjectID == GlobalData.ProjectID &&
                      s.WarehouseID == GlobalData.WarehouseID &&
                      s.SupplierID == (supplierID == -1 ? s.SupplierID : supplierID) &&
                      s.IsHistory == 0
                      select s).FirstOrDefault();
            if (component == null && supply == null)
            {
                //模糊查询供货
                Supply[] supplies = (from s in wmsEntities.Supply
                                     where s.No.Contains(supplyNoOrComponentName) &&
                                     s.ProjectID == GlobalData.ProjectID &&
                                     s.WarehouseID == GlobalData.WarehouseID &&
                                     s.SupplierID == (supplierID == -1 ? s.SupplierID : supplierID) &&
                                     s.IsHistory == 0
                                     select s).ToArray();
                //模糊查询零件
                DataAccess.Component[] components = (from c in wmsEntities.Component
                                                     where c.Name.Contains(supplyNoOrComponentName) &&
                                                     (from s in wmsEntities.Supply
                                                      where s.ComponentID == c.ID &&
                                                      s.ProjectID == GlobalData.ProjectID &&
                                                      s.WarehouseID == GlobalData.WarehouseID &&
                                                      s.SupplierID == (supplierID == -1 ? s.SupplierID : supplierID)
                                                      select s).Count() > 0
                                                     select c).ToArray();

                if (supplies.Length + components.Length == 0)
                {
                    component    = null;
                    supply       = null;
                    errorMessage = "未找到零件:" + supplyNoOrComponentName;
                    return(false);
                }
                //Supply或Component不唯一的情况
                if (supplies.Length + components.Length != 1)
                {
                    object selectedObj =
                        FormChooseAmbiguousSupplyOrComponent.ChooseAmbiguousSupplyOrComponent(
                            components,
                            supplies,
                            supplyNoOrComponentName);
                    if (selectedObj == null)
                    {
                        errorMessage = "用户取消了导入";
                        return(false);
                    }
                    else if (selectedObj is DataAccess.Component)
                    {
                        component = selectedObj as DataAccess.Component;
                    }
                    else if (selectedObj is Supply)
                    {
                        supply = selectedObj as Supply;
                    }
                    else
                    {
                        throw new Exception("FormChooseAmbiguousSupplyOrComponent返回值类型错误");
                    }
                    errorMessage = null;
                    return(true);
                }

                //如果搜索到唯一的零件/供货,则确定就是它。
                if (supplies.Length > 0)
                {
                    supply = supplies[0];
                }
                else
                {
                    component = components[0];
                }
                errorMessage = null;
                return(true);
            }
            errorMessage = null;
            return(true);
        }
示例#57
0
		/// <summary>
		/// Tries to gain the specified cardType from the specified supply into the location and position of the deck specified
		/// </summary>
		/// <param name="supply">The supply pile to gain from</param>
		/// <param name="cardType">The card type we're trying to gain</param>
		/// <param name="location">The deck the card should go into</param>
		/// <param name="position">The position into the deck the card should go</param>
		/// <returns>True if the card was actually gained, False otherwise</returns>
		public Boolean Gain(Supply supply, Type cardType, DeckLocation location, DeckPosition position)
		{
			return Gain(supply, cardType, location, position, false);
		}
示例#58
0
 public void Play(Player p, Supply s)
 {
     p.ExpandHand(3);
 }
示例#59
0
		public Boolean Buy(Supply supply)
		{
			Card supplyCard = supply.TopCard;

			PlayerMode previousMode = this.PlayerMode;
			this.PlayerMode = Players.PlayerMode.Buying;
			Boolean cancelled = false;
			if (CardBuying != null)
			{
				CardBuyEventArgs cbea = new CardBuyEventArgs(_Game, supplyCard);
				CardBuying(this, cbea);
				cancelled = cbea.Cancelled;
			}
			if (!cancelled)
			{
				CurrentTurn.Bought(supplyCard);
				supplyCard.Bought(this);
				supply.Bought(this);

				if (CardBought != null)
				{
					CardBuyEventArgs cbea = null;
					List<Object> handledBy = new List<Object>();
					Boolean actionPerformed = false;
					do
					{
						actionPerformed = false;
						cbea = new CardBuyEventArgs(_Game, supplyCard);
						cbea.HandledBy.AddRange(handledBy);
						CardBought(this, cbea);
						handledBy = cbea.HandledBy;

						Boolean isAnyRequired = false;
						List<String> options = new List<String>();
						IEnumerable<Type> cardTypes = cbea.Actions.Keys;
						foreach (Type key in cardTypes)
						{
							options.Add(cbea.Actions[key].Text);
							isAnyRequired |= cbea.Actions[key].IsRequired;
						}

						if (options.Count > 0)
						{
							options.Sort();
							Choice choice = new Choice(String.Format("You bought {0}", supplyCard), null, new CardCollection() { supplyCard }, options, this, cbea, false, isAnyRequired ? 1 : 0, 1);
							ChoiceResult result = this.MakeChoice(choice);

							if (result.Options.Count > 0)
							{
								cbea.Actions.First(kvp => kvp.Value.Text == result.Options[0]).Value.Method(this, ref cbea);
								actionPerformed = true;
							}
						}

					} while (CardBought != null && actionPerformed);
				}
			}

			if (CardBuyFinished != null)
			{
				CardBuyEventArgs cbea = new CardBuyEventArgs(_Game, supplyCard);
				cbea.Cancelled = cancelled;
				CardBuyFinished(this, cbea);
			}

			if (!cancelled)
			{
				this.Gain(supply, true);

				this.SpendCurrency(new Currency(_Game.ComputeCost(supplyCard)));
				this.Buys--;
			}

			this.PlayerMode = previousMode;
			return cancelled;
		}
 public Boolean updateSupplyByManager(Supply supply)
 {
     return(supplyDao.updateSupplyByManager(supply));
 }