예제 #1
0
 /// <summary>The handle trade data pushed event.</summary>
 /// <param name="trades">The trade data.</param>
 private void HandleTradeDataPushedEvent(TradeData[] trades)
 {
     foreach (var trade in trades)
     {
         this.Trades.Add(trade);
     }
 }
예제 #2
0
        public void MZ_PreviewChargeDllNew(TradeData tradeData)
        {
            tradeData.WorkID = LoginUserInfo.WorkId;

            dicStr.Clear();
            dicStr.Add(InputType.TradeData, JsonHelper.SerializeObject(tradeData));

            ResultClass resultClass = MIInterFaceFactory.MZ_PreviewCharge(input);

            if (resultClass.bSucess)
            {
                Dictionary <string, string> resultDic = (Dictionary <string, string>)resultClass.oResult;
                iFrmMITest.PreviewCharge(resultDic);
            }
            else
            {
                MessageBoxShowError("异常!" + resultClass.sRemarks);
            }
        }
예제 #3
0
        public void Load()
        {
            try
            {
                if (File.Exists(path) == true)
                {
                    XElement root = XElement.Load(path);
                    foreach (var item in root.Elements())
                    {
                        TradeData data = new TradeData();
                        data.BuyId = item.Attribute(XmlConstants.BuyId).Value;
                        Decimal.TryParse(item.Attribute(XmlConstants.BuyPrice).Value, out data.BuyPrice);
                        DateTime.TryParse(item.Attribute(XmlConstants.BuyTime).Value, out data.BuyTime);


                        data.SellId = item.Attribute(XmlConstants.SellId).Value;
                        if (item.Attribute(XmlConstants.SellPrice).Value != null)
                        {
                            Decimal.TryParse(item.Attribute(XmlConstants.SellPrice).Value, out data.SellPrice);
                        }

                        if (item.Attribute(XmlConstants.SellTime).Value != null)
                        {
                            DateTime.TryParse(item.Attribute(XmlConstants.SellTime).Value, out data.SellTime);
                        }

                        if (item.Attribute(XmlConstants.Profit).Value != null)
                        {
                            Decimal.TryParse(item.Attribute(XmlConstants.Profit).Value, out data.Profit);
                        }

                        if (item.Attribute(XmlConstants.TradeTime).Value != null)
                        {
                            TimeSpan.TryParse(item.Attribute(XmlConstants.TradeTime).Value, out data.TradeTime);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex = null;
            }
        }
예제 #4
0
        void HandleClearTradeItem(ClearTradeItem clearTradeItem)
        {
            TradeData my_trade = GetPlayer().GetTradeData();

            if (my_trade == null)
            {
                return;
            }

            my_trade.UpdateClientStateIndex();

            // invalid slot number
            if (clearTradeItem.TradeSlot >= (byte)TradeSlots.Count)
            {
                return;
            }

            my_trade.SetItem((TradeSlots)clearTradeItem.TradeSlot, null);
        }
예제 #5
0
        public void Equals_NullValue_NoException()
        {
            // arrange
            var date   = new DateTime(2013, 5, 20);
            var open   = new decimal(30.16);
            var high   = new decimal(30.39);
            var low    = new decimal(30.02);
            var close  = new decimal(30.17);
            var volume = 1478200;

            // act
            var       data1 = new TradeData(date, open, high, low, close, volume);
            TradeData data2 = null;

            // assert
            Assert.IsFalse(data1.Equals(data2));
            Assert.IsFalse(data1 == data2);
            Assert.AreNotEqual(data1, data2);
        }
예제 #6
0
        public virtual bool IsCargoInHolds(TradeData data)
        {
            var statefulIDs = data.CargoData.StatefulCargo.Select(c => c.Id).ToList();

            if (statefulIDs.Count > 0 && !IsCargoInHolds(statefulIDs))
            {
                return(false);
            }

            foreach (var c in data.CargoData.StatelessCargo)
            {
                if (!IsCargoInHolds(c.CargoType, c.Quantity))
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #7
0
        private static async Task Main()
        {
            Console.WriteLine("\nEXAMPLE 5 : TOPICS : PRODUCER");

            var connectionFactory = new ConnectionFactory
            {
                HostName = "localhost",
                UserName = "******",
                Password = "******"
            };

            using var connection = connectionFactory.CreateConnection();

            using var channel = connection.CreateModel();

            const string ExchangeName = "example5_trades_exchange";

            channel.ExchangeDeclare(exchange: ExchangeName, type: ExchangeType.Topic);

            while (true)
            {
                var trade = TradeData.GetFakeTrade();

                var topic = $"{trade.NormalizedRegion}.{trade.NormalizedIndustry}.{trade.NormalizedAction}";

                channel.BasicPublish(
                    exchange: ExchangeName,
                    routingKey: topic,
                    body: trade.ToBytes());

                DisplayInfo <Trade>
                .For(trade)
                .SetExchange(ExchangeName)
                .SetRoutingKey(topic)
                .SetTopic(topic)
                .SetVirtualHost(connectionFactory.VirtualHost)
                .Display(Color.Cyan);

                await Task.Delay(millisecondsDelay : 5000);
            }
        }
예제 #8
0
        //Place Buy Limit Orders
        public void PlaceBuyLimitOrders()
        {
            //Place Buy Limit Orders
            for (int OrderCount = 0; OrderCount < NumberOfOrders; OrderCount++)
            {
                try
                {
                    TradeData data = new TradeData
                    {
                        tradeType      = TradeType.Buy,
                        symbol         = Bot.Symbol,
                        volume         = SetVolume(OrderCount),
                        entryPrice     = CalcBuyEntryPrice(OrderCount),
                        label          = BotState.BotId + "-" + Utils.GetTimeStamp(Bot) + BotState.GetMarketName() + "-SWF#" + OrderCount,
                        stopLossPips   = SetPendingOrderStopLossPips(OrderCount, NumberOfOrders),
                        takeProfitPips = DefaultTakeProfitPips * (1 / Bot.Symbol.TickSize)
                    };

                    if (data == null)
                    {
                        continue;
                    }

                    //Check that entry price is valid
                    if (data.entryPrice < Bot.Symbol.Bid)
                    {
                        Bot.PlaceLimitOrderAsync(data.tradeType, data.symbol, data.volume, data.entryPrice, data.label, data.stopLossPips, data.takeProfitPips, OnPlaceBuyLimitOrderOperationComplete);
                    }
                    else
                    {
                        //Tick price has 'jumped' - therefore avoid placing all PendingOrders by re-calculating the OrderCount to the equivelant entry point.
                        OrderCount = CalcNewOrderCount(OrderCount, Bot.Symbol.Bid);
                        Bot.ExecuteMarketOrderAsync(data.tradeType, data.symbol, data.volume, data.label + "X", data.stopLossPips, data.takeProfitPips, OnBuyTradeOperationComplete);
                    }
                }
                catch (Exception e)
                {
                    Bot.Print("Failed to place buy limit order: " + e.Message);
                }
            }
        }
예제 #9
0
        public void Constuctor_TradeDataList_NoException()
        {
            // arrange
            var date     = new DateTime(2013, 5, 20);
            var open     = new decimal(30.16);
            var high     = new decimal(30.39);
            var low      = new decimal(30.02);
            var close    = new decimal(30.17);
            var volume   = 1478200;
            var data     = new TradeData(date, open, high, low, close, volume);
            var dataList = new List <TradeData> {
                data, data, data
            };

            // act
            var package = new TradeDataPackage(dataList);

            // assert
            Assert.IsTrue(package.TradeDataList.Count == dataList.Count);
            Assert.AreSame(package.TradeDataList, dataList);
        }
예제 #10
0
        public static DocumentBuilder Run()
        {
            string   firmJsonFile    = CheckFile(Path.Combine("Content", "firm-data.json"));
            string   firmJsonContent = File.ReadAllText(firmJsonFile);
            FirmData firmData        =
                JsonConvert.DeserializeObject <FirmData>(firmJsonContent);

            string tradeJsonFile    = CheckFile(Path.Combine("Content", "trade-data.json"));
            string tradeJsonContent = File.ReadAllText(tradeJsonFile);

            TradeData tradeData =
                JsonConvert.DeserializeObject <TradeData>(tradeJsonContent);

            TradeConfirmationBuilder TradeConfirmationBuilder =
                new TradeConfirmationBuilder();

            TradeConfirmationBuilder.FirmData  = firmData;
            TradeConfirmationBuilder.TradeData = tradeData;

            return(TradeConfirmationBuilder.Build());
        }
예제 #11
0
        public void Constuctor_NoException()
        {
            // arrange
            var date   = new DateTime(2013, 5, 20);
            var open   = new decimal(30.16);
            var high   = new decimal(30.39);
            var low    = new decimal(30.02);
            var close  = new decimal(30.17);
            var volume = 1478200;

            // act
            var data = new TradeData(date, open, high, low, close, volume);

            // assert
            Assert.AreEqual(date, data.Date);
            Assert.AreEqual(open, data.Open);
            Assert.AreEqual(high, data.High);
            Assert.AreEqual(low, data.Low);
            Assert.AreEqual(close, data.Close);
            Assert.AreEqual(volume, data.Volume);
        }
예제 #12
0
        public void Parse_AllCorrectValues_NoException()
        {
            // arrange
            var          date             = new DateTime(2013, 5, 20);
            var          open             = new decimal(30.16);
            var          high             = new decimal(30.39);
            var          low              = new decimal(30.02);
            var          close            = new decimal(30.17);
            var          volume           = 1478200;
            const string correctCsvString = "2013-5-20,30.16,30.39,30.02,30.17,1478200";
            var          corectValues     = correctCsvString.Split(',');

            // act
            var data = TradeData.Parse(corectValues);

            // assert
            Assert.AreEqual(date, data.Date);
            Assert.AreEqual(open, data.Open);
            Assert.AreEqual(high, data.High);
            Assert.AreEqual(low, data.Low);
            Assert.AreEqual(close, data.Close);
            Assert.AreEqual(volume, data.Volume);
        }
        /// <summary>
        /// Converts value of one type to another.
        /// </summary>
        /// <param name="source">Value to convert.</param>
        /// <returns>Converted value.</returns>
        public DataTransfer Convert(string source)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source), "Source must be not null.");
            }

            var parameters = source.Split(',');

            if (parameters.Length != AmountOfParameters)
            {
                throw new FormatException("Invalid data format.");
            }

            if (parameters[0].Length != CodeLength)
            {
                throw new FormatException("Invalid data format.");
            }

            string countryCode  = parameters[0].Substring(0, 3);
            string currencyCode = parameters[0].Substring(3, 3);

            if (!int.TryParse(parameters[1], out int amountOfTrades))
            {
                throw new FormatException("Invalid data format.");
            }

            if (!decimal.TryParse(parameters[2], out decimal cost))
            {
                throw new FormatException("Invalid data format");
            }

            DataTransfer dataTransfer = new TradeData(countryCode, currencyCode, amountOfTrades, cost);

            this.validator.Validate(dataTransfer);
            return(dataTransfer);
        }
        public ActionResult TradesPerCoin(string id, string basecurrency)
        {
            string apikey    = (string)Session["apikey"];
            string apisecret = (string)Session["apisecret"];

            if (string.IsNullOrEmpty(apikey) || string.IsNullOrEmpty(apisecret))
            {
                return(RedirectToAction("Index"));
            }

            var inp = new TradeInput
            {
                ApiKey       = apikey,
                ApiSecret    = apisecret,
                Coin         = id,
                BaseCurrency = basecurrency,
                NoOfTrades   = 200
            };
            TradeData tradedata = CalculateTradeData(inp);

            //ViewBag.Result = outp;
            ViewBag.TradeData = tradedata;
            return(View(inp));
        }
예제 #15
0
        /// <summary>
        /// 处理订单生成时的相应逻辑
        /// </summary>
        public void Start()
        {
            //获取店铺的基础数据
            ShopData data = new ShopData();
            ShopInfo shop = data.ShopInfoGetByNick(TradeInfo.Nick);

            //目前只做虚拟店铺的逻辑
            if (shop.IsXuni == "1")
            {
                //通过TOP接口查询该订单的详细数据并记录到数据库中
                TopApiHaoping api = new TopApiHaoping(shop.Session);
                //特殊判断催单订单不获取物流信息
                TradeInfo.Status = "CuiDan";
                Trade trade = api.GetTradeByTid(TradeInfo);

                //判断该订单是否存在
                TradeData dbTrade = new TradeData();
                if (!dbTrade.CheckTradeExits(trade))
                {
                    //更新该订单的评价时间
                    dbTrade.InsertTradeInfo(trade);
                }
            }
        }
예제 #16
0
 public WebSocketMessage(TradeData data)
 {
     Data = data;
 }
예제 #17
0
        public void Start(string index)
        {
            //获取目前正在使用的卖家(需要改成全部卖家,否则物流状态无法获取)
            ShopData        dbShop = new ShopData();
            List <ShopInfo> list   = dbShop.GetShopInfoListShippingAlert(index);

            //循环判定这些卖家的订单是否物流到货
            for (int i = 0; i < list.Count; i++)
            {
                try
                {
                    ShopInfo shop = list[i];
                    //获取那些状态是发货中且没发过短信的订单给予提示
                    TradeData    dbTrade   = new TradeData();
                    List <Trade> listTrade = dbTrade.GetShippingTrade(shop);

                    Console.Write(listTrade.Count.ToString() + "\r\n");
                    for (int j = 0; j < listTrade.Count; j++)
                    {
                        //如果是晚上10点到早上9点这个时间端内,不发送物流提醒短信
                        if (DateTime.Now.Hour > 8 && DateTime.Now.Hour < 22)
                        {
                            Trade trade = listTrade[j];

                            //判断如果是分销的订单,则不处理
                            if (trade.OrderType.ToLower() == "fenxiao")
                            {
                                continue;
                            }

                            //获取该订单的物流状态
                            TopApiHaoping api    = new TopApiHaoping(shop.Session);
                            string        status = api.GetShippingStatusByTid(listTrade[j]);

                            Console.Write(status + "\r\n");
                            //如果该物流信息不存在
                            if (status.IndexOf("不存在") != -1)
                            {
                                //如果该物流公司不支持查询则更新为self
                                dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                                continue;
                            }

                            trade = api.GetOrderShippingInfo(trade);

                            if (!dbTrade.IsTaobaoCompany(trade))
                            {
                                //如果不是淘宝合作物流则直接更新
                                dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                            }
                            else
                            {
                                //根据服务器的物流状态进行判断,如果物流状态是已签收
                                if (status == "ACCEPTED_BY_RECEIVER" || status == "ACCEPTING" || status == "ACCEPTED")
                                {
                                    string result = api.GetShippingStatusDetailByTid(trade);
                                    Console.Write("【" + result + "】\r\n");
                                    //如果订单不是服务器错误
                                    if (result.IndexOf("company-not-support") != -1)
                                    {
                                        //如果该物流公司不支持查询则更新为self
                                        dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                                        continue;
                                    }

                                    //再根据订单的详细物流信息判断签收的状态
                                    if (result.IndexOf("签收人") != -1 || result.IndexOf(" 签收") != -1 || result.IndexOf(" 已签收") != -1 || result.IndexOf(" 妥投") != -1 || result.IndexOf("正常签收") != -1)
                                    {
                                        //如果物流已经签收了则更新对应订单状态
                                        trade.DeliveryEnd = utils.GetShippingEndTime(result);;
                                        trade.DeliveryMsg = result;

                                        //如果物流到货时间还是为空
                                        if (trade.DeliveryEnd == "")
                                        {
                                            LogData dbLog = new LogData();
                                            dbLog.InsertErrorLog(trade.Nick, "deliveryDateNull", "", result, "");
                                            continue;
                                        }

                                        //更新物流到货时间
                                        dbTrade.UpdateTradeShippingStatusSystem(trade, status);

                                        //发送短信-上LOCK锁定
                                        lock (ShippingSuccess.padlock1)
                                        {
                                            //判断同类型的短信该客户今天是否只收到一条
                                            ShopData db = new ShopData();
                                            if (!db.IsSendMsgOrder(trade, "shipping") && !db.IsSendMsgNear(trade, "shipping"))
                                            {
                                                //判断该用户是否开启了发货短信
                                                if (shop.MsgIsShipping == "1" && int.Parse(shop.MsgCount) > 0)
                                                {
                                                    //发送短信
                                                    //string msg = Message.GetMsg(shop.MsgShippingContent, shop.MsgShopName, trade.BuyNick, shop.IsCoupon);
                                                    string msg       = Message.GetMsg(shop, trade, shop.MsgShippingContent);
                                                    string msgResult = Message.Send(trade.Mobile, msg);

                                                    //记录
                                                    if (msgResult != "0")
                                                    {
                                                        db.InsertShopMsgLog(shop, trade, msg, msgResult, "shipping");
                                                    }
                                                    else
                                                    {
                                                        db.InsertShopErrMsgLog(shop, trade, msg, msgResult, "shipping");
                                                    }

                                                    shop.MsgCount = (int.Parse(shop.MsgCount) - 1).ToString();
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            //return;
                        }
                    }
                }
                catch { }
            }
        }
        private static TradeData CalculateTradeData(TradeInput inp)
        {
            var bittrex  = new Exchange();
            var coin     = inp.Coin.ToUpper();
            var basecurr = inp.BaseCurrency;

            bittrex.Initialise(new ExchangeContext {
                ApiKey = inp.ApiKey, Secret = inp.ApiSecret, QuoteCurrency = basecurr.ToUpper(), Simulate = false
            });
            var    tick = bittrex.GetTicker(coin);
            var    hist = bittrex.GetOrderHistory(coin, inp.NoOfTrades).OrderBy(x => x.TimeStamp).Take(inp.NoOfTrades);
            string outp = "";

            //    var buys = hist.Where(x=>x.OrderType == OpenOrderType.Limit_Buy);
            //    var sells = hist.Where(x=>x.OrderType == OpenOrderType.Limit_Sell);
            //    var buyQuantity = buys.Sum(x=>x.Quantity-x.QuantityRemaining);
            //    buyQuantity.Dump("buyq");
            decimal averageBuy       = 0;
            decimal buyQuantity      = 0;
            decimal totalBuyQuantity = 0;
            decimal averageSell      = 0;

            bool first     = true;
            var  tradedata = new TradeData()
            {
                RealizedTrades = new List <RealizedTradeData>()
            };

            foreach (var h in hist)
            {
                if (h.OrderType == OpenOrderType.Limit_Buy)
                {
                    decimal prevBuyQ = buyQuantity;
                    buyQuantity      += h.Quantity - h.QuantityRemaining;
                    totalBuyQuantity += h.Quantity - h.QuantityRemaining;
                    averageBuy        = (averageBuy * prevBuyQ) / buyQuantity + (h.PricePerUnit * ((h.Quantity - h.QuantityRemaining) / buyQuantity));
                    //outp += $"Bought {h.Quantity - h.QuantityRemaining} {coin} at {h.PricePerUnit} - averagebuy: {averageBuy:0.#########} Value:{h.Price} date:{h.TimeStamp}<br/>";
                    tradedata.RealizedTrades.Add(new RealizedTradeData
                    {
                        Quantity     = h.Quantity - h.QuantityRemaining,
                        AverageBuy   = averageBuy,
                        PricePerUnit = h.PricePerUnit,
                        TotalPrice   = h.Price,
                        TimeStamp    = h.TimeStamp,
                        BuySell      = "Buy"
                    });
                    first = false;
                }
                else
                {
                    var sold = h.Quantity - h.QuantityRemaining;
                    if (first)
                    {
                        //outp += $"First order is sell, ignoring!!! Sold {sold} at {h.PricePerUnit} date: {h.TimeStamp}<br/>";
                    }
                    else
                    {
                        var pl = ((h.PricePerUnit - averageBuy) / averageBuy) * 100;

                        var plValue2 = h.PricePerUnit * h.Quantity - (averageBuy * h.Quantity);
                        buyQuantity -= sold;
                        //  averageSell = (averageSell * prevBuyQ) / buyQuantity + (h.PricePerUnit * ((h.Quantity - h.QuantityRemaining) / buyQuantity));
                        // outp += $"Sold {sold} at {h.PricePerUnit} P/L:{pl:0.##}% remaining:{buyQuantity} Value: {h.Price} date: {h.TimeStamp}<br/>";
                        tradedata.RealizedTrades.Add(new RealizedTradeData
                        {
                            Quantity          = sold,
                            RemainingQuantity = buyQuantity,
                            AverageBuy        = averageBuy,
                            ProfitLoss        = pl,
                            PricePerUnit      = h.PricePerUnit,
                            TotalPrice        = h.Price,
                            TimeStamp         = h.TimeStamp,
                            ProfitLossValue   = plValue2,
                            BuySell           = "Sell"
                        });
                    }
                }
            }
            if (buyQuantity > 0)
            {
                decimal unrealized = ((tick.Last - averageBuy) / averageBuy) * 100;
                outp += $"<h3>Unrealized P/L: last:{tick.Last} {unrealized:0.##} Quantity: {buyQuantity} Value: {buyQuantity * tick.Last}</h3>";
                tradedata.UnrealizedTrade = new TotalTrade
                {
                    ProfitLoss        = unrealized,
                    ProfitLossValue   = (tick.Last * buyQuantity) - (averageBuy * buyQuantity),
                    RemainingQuantity = buyQuantity,
                    Value             = buyQuantity * tick.Last,
                    LastPrice         = tick.Last
                };
            }
            // realized p/l
            //var soldTotalPrice = tradedata.RealizedTrades.Where(x => x.BuySell == "Sell").Sum(x => x.TotalPrice);
            //var soldTotalQuantity = tradedata.RealizedTrades.Where(x => x.BuySell == "Sell").Sum(x => x.Quantity);
            //var totalPriceFromAverageBuy = averageBuy * soldTotalQuantity;
            //var realizedPL = ((soldTotalPrice-totalPriceFromAverageBuy)/totalPriceFromAverageBuy)*100;

            IEnumerable <RealizedTradeData> sells = tradedata.RealizedTrades.Where(x => x.BuySell == "Sell").ToList();
            var soldTotalQuantity = sells.Sum(x => x.Quantity);
            var realizedPL        = sells.Sum(x => x.ProfitLoss * (x.Quantity / soldTotalQuantity));
            var realizedPLValue   = sells.Sum(x => x.ProfitLossValue);
            var value             = sells.Sum(x => x.TotalPrice);

            tradedata.RealizedTrade = new TotalTrade
            {
                ProfitLoss        = realizedPL,
                RemainingQuantity = soldTotalQuantity,
                Value             = value,
                ProfitLossValue   = realizedPLValue
            };
            return(tradedata);
        }
예제 #19
0
        public void Start()
        {
            //获取目前正在使用的卖家
            ShopData        dbShop = new ShopData();
            List <ShopInfo> list   = dbShop.GetShopInfoListAlert();

            //循环判定卖家是否到提醒发货时间了
            Console.Write(list.Count.ToString() + "\r\n");
            for (int i = 0; i < list.Count; i++)
            {
                ShopInfo shop = list[i];
                Console.Write(shop.Nick + "-" + shop.MsgReviewTime + "-" + DateTime.Now.Hour.ToString() + "\r\n");
                if (DateTime.Now.Hour.ToString() == list[i].MsgReviewTime || shop.IsXuni == "1")
                {
                    //获取那些延迟不确认且没发过短信的订单给予提示
                    TradeData    dbTrade   = new TradeData();
                    List <Trade> listTrade = new List <Trade>();

                    if (shop.IsXuni == "1")
                    {
                        //如果是虚拟商品
                        listTrade = dbTrade.GetUnconfirmTradeXuni(shop);
                    }
                    else
                    {
                        listTrade = dbTrade.GetUnconfirmTrade(shop);
                    }

                    Console.Write(listTrade.Count.ToString() + "\r\n");
                    for (int j = 0; j < listTrade.Count; j++)
                    {
                        Trade trade = listTrade[j];

                        //判断如果是分销的订单,则不处理
                        if (trade.OrderType.ToLower() == "fenxiao")
                        {
                            return;
                        }

                        //发送短信-上LOCK锁定
                        lock (padlock4)
                        {
                            //判断同类型的短信该客户今天是否只收到一条
                            ShopData db = new ShopData();
                            if (!db.IsSendMsgOrder(trade, "review") && !db.IsSendMsgToday(trade, "review"))
                            {
                                //判断该用户是否开启了发货短信
                                if (shop.MsgIsReview == "1" && int.Parse(shop.MsgCount) > 0)
                                {
                                    //发送短信
                                    //string msg = Message.GetMsg(shop.MsgReviewContent, shop.MsgShopName, trade.BuyNick, shop.IsCoupon);
                                    string msg       = Message.GetMsg(shop, trade, shop.MsgReviewContent);
                                    string msgResult = Message.Send(trade.Mobile, msg);

                                    //记录
                                    if (msgResult != "0")
                                    {
                                        db.InsertShopMsgLog(shop, trade, msg, msgResult, "review");
                                    }
                                    else
                                    {
                                        db.InsertShopErrMsgLog(shop, trade, msg, msgResult, "review");
                                    }
                                    shop.MsgCount = (int.Parse(shop.MsgCount) - 1).ToString();
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #20
0
        void HandleAcceptTrade(AcceptTrade acceptTrade)
        {
            TradeData my_trade = GetPlayer().GetTradeData();

            if (my_trade == null)
            {
                return;
            }

            Player trader = my_trade.GetTrader();

            TradeData his_trade = trader.GetTradeData();

            if (his_trade == null)
            {
                return;
            }

            Item[] myItems  = new Item[(int)TradeSlots.Count];
            Item[] hisItems = new Item[(int)TradeSlots.Count];

            // set before checks for propertly undo at problems (it already set in to client)
            my_trade.SetAccepted(true);

            TradeStatusPkt info = new TradeStatusPkt();

            if (his_trade.GetServerStateIndex() != acceptTrade.StateIndex)
            {
                info.Status = TradeStatus.StateChanged;
                SendTradeStatus(info);
                my_trade.SetAccepted(false);
                return;
            }

            if (!GetPlayer().IsWithinDistInMap(trader, 11.11f, false))
            {
                info.Status = TradeStatus.TooFarAway;
                SendTradeStatus(info);
                my_trade.SetAccepted(false);
                return;
            }

            // not accept case incorrect money amount
            if (!GetPlayer().HasEnoughMoney(my_trade.GetMoney()))
            {
                info.Status    = TradeStatus.Failed;
                info.BagResult = InventoryResult.NotEnoughMoney;
                SendTradeStatus(info);
                my_trade.SetAccepted(false, true);
                return;
            }

            // not accept case incorrect money amount
            if (!trader.HasEnoughMoney(his_trade.GetMoney()))
            {
                info.Status    = TradeStatus.Failed;
                info.BagResult = InventoryResult.NotEnoughMoney;
                trader.GetSession().SendTradeStatus(info);
                his_trade.SetAccepted(false, true);
                return;
            }

            if (GetPlayer().GetMoney() >= PlayerConst.MaxMoneyAmount - his_trade.GetMoney())
            {
                info.Status    = TradeStatus.Failed;
                info.BagResult = InventoryResult.TooMuchGold;
                SendTradeStatus(info);
                my_trade.SetAccepted(false, true);
                return;
            }

            if (trader.GetMoney() >= PlayerConst.MaxMoneyAmount - my_trade.GetMoney())
            {
                info.Status    = TradeStatus.Failed;
                info.BagResult = InventoryResult.TooMuchGold;
                trader.GetSession().SendTradeStatus(info);
                his_trade.SetAccepted(false, true);
                return;
            }

            // not accept if some items now can't be trade (cheating)
            for (byte i = 0; i < (byte)TradeSlots.Count; ++i)
            {
                Item item = my_trade.GetItem((TradeSlots)i);
                if (item)
                {
                    if (!item.CanBeTraded(false, true))
                    {
                        info.Status = TradeStatus.Cancelled;
                        SendTradeStatus(info);
                        return;
                    }

                    if (item.IsBindedNotWith(trader))
                    {
                        info.Status    = TradeStatus.Failed;
                        info.BagResult = InventoryResult.TradeBoundItem;
                        SendTradeStatus(info);
                        return;
                    }
                }
                item = his_trade.GetItem((TradeSlots)i);
                if (item)
                {
                    if (!item.CanBeTraded(false, true))
                    {
                        info.Status = TradeStatus.Cancelled;
                        SendTradeStatus(info);
                        return;
                    }
                }
            }

            if (his_trade.IsAccepted())
            {
                SetAcceptTradeMode(my_trade, his_trade, myItems, hisItems);

                Spell            my_spell   = null;
                SpellCastTargets my_targets = new SpellCastTargets();

                Spell            his_spell   = null;
                SpellCastTargets his_targets = new SpellCastTargets();

                // not accept if spell can't be casted now (cheating)
                uint my_spell_id = my_trade.GetSpell();
                if (my_spell_id != 0)
                {
                    SpellInfo spellEntry = Global.SpellMgr.GetSpellInfo(my_spell_id);
                    Item      castItem   = my_trade.GetSpellCastItem();

                    if (spellEntry == null || !his_trade.GetItem(TradeSlots.NonTraded) ||
                        (my_trade.HasSpellCastItem() && !castItem))
                    {
                        ClearAcceptTradeMode(my_trade, his_trade);
                        ClearAcceptTradeMode(myItems, hisItems);

                        my_trade.SetSpell(0);
                        return;
                    }

                    my_spell            = new Spell(GetPlayer(), spellEntry, TriggerCastFlags.FullMask);
                    my_spell.m_CastItem = castItem;
                    my_targets.SetTradeItemTarget(GetPlayer());
                    my_spell.m_targets = my_targets;

                    SpellCastResult res = my_spell.CheckCast(true);
                    if (res != SpellCastResult.SpellCastOk)
                    {
                        my_spell.SendCastResult(res);

                        ClearAcceptTradeMode(my_trade, his_trade);
                        ClearAcceptTradeMode(myItems, hisItems);

                        my_spell.Dispose();
                        my_trade.SetSpell(0);
                        return;
                    }
                }

                // not accept if spell can't be casted now (cheating)
                uint his_spell_id = his_trade.GetSpell();
                if (his_spell_id != 0)
                {
                    SpellInfo spellEntry = Global.SpellMgr.GetSpellInfo(his_spell_id);
                    Item      castItem   = his_trade.GetSpellCastItem();

                    if (spellEntry == null || !my_trade.GetItem(TradeSlots.NonTraded) || (his_trade.HasSpellCastItem() && !castItem))
                    {
                        his_trade.SetSpell(0);

                        ClearAcceptTradeMode(my_trade, his_trade);
                        ClearAcceptTradeMode(myItems, hisItems);
                        return;
                    }

                    his_spell            = new Spell(trader, spellEntry, TriggerCastFlags.FullMask);
                    his_spell.m_CastItem = castItem;
                    his_targets.SetTradeItemTarget(trader);
                    his_spell.m_targets = his_targets;

                    SpellCastResult res = his_spell.CheckCast(true);
                    if (res != SpellCastResult.SpellCastOk)
                    {
                        his_spell.SendCastResult(res);

                        ClearAcceptTradeMode(my_trade, his_trade);
                        ClearAcceptTradeMode(myItems, hisItems);

                        my_spell.Dispose();
                        his_spell.Dispose();

                        his_trade.SetSpell(0);
                        return;
                    }
                }

                // inform partner client
                info.Status = TradeStatus.Accepted;
                trader.GetSession().SendTradeStatus(info);

                // test if item will fit in each inventory
                TradeStatusPkt myCanCompleteInfo  = new TradeStatusPkt();
                TradeStatusPkt hisCanCompleteInfo = new TradeStatusPkt();
                hisCanCompleteInfo.BagResult = trader.CanStoreItems(myItems, (int)TradeSlots.TradedCount, ref hisCanCompleteInfo.ItemID);
                myCanCompleteInfo.BagResult  = GetPlayer().CanStoreItems(hisItems, (int)TradeSlots.TradedCount, ref myCanCompleteInfo.ItemID);

                ClearAcceptTradeMode(myItems, hisItems);

                // in case of missing space report error
                if (myCanCompleteInfo.BagResult != InventoryResult.Ok)
                {
                    ClearAcceptTradeMode(my_trade, his_trade);

                    myCanCompleteInfo.Status = TradeStatus.Failed;
                    trader.GetSession().SendTradeStatus(myCanCompleteInfo);
                    myCanCompleteInfo.FailureForYou = true;
                    SendTradeStatus(myCanCompleteInfo);
                    my_trade.SetAccepted(false);
                    his_trade.SetAccepted(false);
                    return;
                }
                else if (hisCanCompleteInfo.BagResult != InventoryResult.Ok)
                {
                    ClearAcceptTradeMode(my_trade, his_trade);

                    hisCanCompleteInfo.Status = TradeStatus.Failed;
                    SendTradeStatus(hisCanCompleteInfo);
                    hisCanCompleteInfo.FailureForYou = true;
                    trader.GetSession().SendTradeStatus(hisCanCompleteInfo);
                    my_trade.SetAccepted(false);
                    his_trade.SetAccepted(false);
                    return;
                }

                // execute trade: 1. remove
                for (byte i = 0; i < (int)TradeSlots.TradedCount; ++i)
                {
                    if (myItems[i])
                    {
                        myItems[i].SetGiftCreator(GetPlayer().GetGUID());
                        GetPlayer().MoveItemFromInventory(myItems[i].GetBagSlot(), myItems[i].GetSlot(), true);
                    }
                    if (hisItems[i])
                    {
                        hisItems[i].SetGiftCreator(trader.GetGUID());
                        trader.MoveItemFromInventory(hisItems[i].GetBagSlot(), hisItems[i].GetSlot(), true);
                    }
                }

                // execute trade: 2. store
                MoveItems(myItems, hisItems);

                // logging money
                if (HasPermission(RBACPermissions.LogGmTrade))
                {
                    if (my_trade.GetMoney() > 0)
                    {
                        Log.outCommand(GetPlayer().GetSession().GetAccountId(), "GM {0} (Account: {1}) give money (Amount: {2}) to player: {3} (Account: {4})",
                                       GetPlayer().GetName(), GetPlayer().GetSession().GetAccountId(), my_trade.GetMoney(), trader.GetName(), trader.GetSession().GetAccountId());
                    }

                    if (his_trade.GetMoney() > 0)
                    {
                        Log.outCommand(GetPlayer().GetSession().GetAccountId(), "GM {0} (Account: {1}) give money (Amount: {2}) to player: {3} (Account: {4})",
                                       trader.GetName(), trader.GetSession().GetAccountId(), his_trade.GetMoney(), GetPlayer().GetName(), GetPlayer().GetSession().GetAccountId());
                    }
                }


                // update money
                GetPlayer().ModifyMoney(-(long)my_trade.GetMoney());
                GetPlayer().ModifyMoney((long)his_trade.GetMoney());
                trader.ModifyMoney(-(long)his_trade.GetMoney());
                trader.ModifyMoney((long)my_trade.GetMoney());

                if (my_spell)
                {
                    my_spell.Prepare(my_targets);
                }

                if (his_spell)
                {
                    his_spell.Prepare(his_targets);
                }

                // cleanup
                ClearAcceptTradeMode(my_trade, his_trade);
                GetPlayer().SetTradeData(null);
                trader.SetTradeData(null);

                // desynchronized with the other saves here (SaveInventoryAndGoldToDB() not have own transaction guards)
                SQLTransaction trans = new SQLTransaction();
                GetPlayer().SaveInventoryAndGoldToDB(trans);
                trader.SaveInventoryAndGoldToDB(trans);
                DB.Characters.CommitTransaction(trans);

                info.Status = TradeStatus.Complete;
                trader.GetSession().SendTradeStatus(info);
                SendTradeStatus(info);
            }
            else
            {
                info.Status = TradeStatus.Accepted;
                trader.GetSession().SendTradeStatus(info);
            }
        }
예제 #21
0
        public IEnumerable <Trade> GetTrades(TradeDataSource dataSource, TradeData current)
        {
            var fetch = current.Data.GetEnumerator();

            if (!fetch.MoveNext())
            {
                yield break;
            }

            var header = fetch.Current.Select(u => u.ToString()).ToArray();

            var date    = Array.IndexOf(header, "Date(UTC)");
            var type    = Array.IndexOf(header, "Type");
            var asset   = Array.IndexOf(header, "Market");
            var amount  = Array.IndexOf(header, "Amount");
            var total   = Array.IndexOf(header, "Total");
            var fee     = Array.IndexOf(header, "Fee");
            var feeCoin = Array.IndexOf(header, "Fee Coin");

            if (date < 0 || type < 0 || asset < 0 || amount < 0 || fee < 0 || feeCoin < 0 || total < 0)
            {
                yield break;
            }

            var list = new List <Trade>();

            while (fetch.MoveNext())
            {
                var row = fetch.Current;

                if (row.Length < 8 || !ParseCoin(row[asset].ToString(), out var from, out var to))
                {
                    continue;
                }

                var dfee = decimal.Parse(row[fee].ToString(), CultureInfo.InvariantCulture);

                switch (row[type].ToString().ToUpperInvariant())
                {
                case "BUY":
                {
                    var trade = new BuyTrade()
                    {
                        Exchange = this,
                        From     = new Quantity()
                        {
                            Coin  = to,
                            Value = decimal.Parse(row[total].ToString(), CultureInfo.InvariantCulture)
                        },
                        To = new Quantity()
                        {
                            Coin  = from,
                            Value = decimal.Parse(row[amount].ToString(), CultureInfo.InvariantCulture)
                        },
                        Fees = dfee == 0 ? new Quantity[0] : new Quantity[]
                        {
                            new Quantity()
                            {
                                Coin  = ParseCoin(row[feeCoin].ToString()),
                                Value = dfee
                            }
                        },
                        Date = DateTime.ParseExact(row[date].ToString(), "yyyy-MM-dd H:mm:ss", CultureInfo.InvariantCulture)
                    };
                    yield return(trade);

                    break;
                }

                case "SELL":
                {
                    var trade = new SellTrade()
                    {
                        Exchange = this,
                        From     = new Quantity()
                        {
                            Coin  = from,
                            Value = decimal.Parse(row[amount].ToString(), CultureInfo.InvariantCulture)
                        },
                        To = new Quantity()
                        {
                            Coin  = to,
                            Value = decimal.Parse(row[total].ToString(), CultureInfo.InvariantCulture)
                        },
                        Fees = dfee == 0 ? new Quantity[0] : new Quantity[]
                        {
                            new Quantity()
                            {
                                Coin  = ParseCoin(row[feeCoin].ToString()),
                                Value = dfee
                            }
                        },
                        Date = DateTime.ParseExact(row[date].ToString(), "yyyy-MM-dd H:mm:ss", CultureInfo.InvariantCulture)
                    };
                    yield return(trade);

                    break;
                }

                default: throw new ArgumentException(nameof(type));
                }
            }
        }
예제 #22
0
        public IEnumerable <Trade> GetTrades(TradeDataSource dataSource, TradeData current)
        {
            var fetch = current.Data.GetEnumerator();

            if (!fetch.MoveNext())
            {
                yield break;
            }

            var header = fetch.Current.Select(u => u.ToString()).ToArray();

            var vol  = Array.IndexOf(header, "Quantity");
            var pair = Array.IndexOf(header, "Exchange");
            var time = Array.IndexOf(header, "Opened");
            var cost = Array.IndexOf(header, "Price");
            var fee  = Array.IndexOf(header, "CommissionPaid");
            var type = Array.IndexOf(header, "Type");

            if (pair < 0 || time < 0 || fee < 0 || cost < 0 || type < 0 || vol < 0)
            {
                yield break;
            }

            var list = new List <Trade>();

            while (fetch.MoveNext())
            {
                var row = fetch.Current;

                if (!ParseCoin(row[pair].ToString(), out var from, out var to))
                {
                    continue;
                }

                switch (row[type].ToString().ToUpperInvariant())
                {
                case "LIMIT_BUY":
                {
                    yield return(new BuyTrade()
                        {
                            Exchange = this,
                            Date = DateTime.ParseExact(row[time].ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture),
                            From = new Quantity()
                            {
                                Coin = from,
                                Value = decimal.Parse(row[cost].ToString(), CultureInfo.InvariantCulture)
                            },
                            To = new Quantity()
                            {
                                Coin = to,
                                Value = decimal.Parse(row[vol].ToString(), CultureInfo.InvariantCulture)
                            },
                            Fees = new Quantity[]
                            {
                                new Quantity()
                                {
                                    Coin = from,
                                    Value = decimal.Parse(row[fee].ToString(), CultureInfo.InvariantCulture)
                                }
                            }
                        });

                    break;
                }

                case "LIMIT_SELL":
                {
                    yield return(new SellTrade()
                        {
                            Exchange = this,
                            Date = DateTime.ParseExact(row[time].ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture),
                            From = new Quantity()
                            {
                                Coin = to,
                                Value = decimal.Parse(row[vol].ToString(), CultureInfo.InvariantCulture)
                            },
                            To = new Quantity()
                            {
                                Coin = from,
                                Value = decimal.Parse(row[cost].ToString(), CultureInfo.InvariantCulture)
                            },
                            Fees = new Quantity[]
                            {
                                new Quantity()
                                {
                                    Coin = from,
                                    Value = decimal.Parse(row[fee].ToString(), CultureInfo.InvariantCulture)
                                }
                            }
                        });

                    break;
                }

                default: throw new ArgumentException(nameof(type));
                }
            }
        }
예제 #23
0
        private void CompareItems(TradeExportData input, TradeData output)
        {
            Assert.AreEqual(input.StyleNo, output.StyleNo);
            Assert.AreEqual(input.Description1 ?? string.Empty, output.Description1);
            Assert.AreEqual(input.Description2 ?? string.Empty, output.Description2);
            Assert.AreEqual(input.Description4 ?? string.Empty, output.Description4);
            Assert.AreEqual(input.PrimaryVendor ?? string.Empty, output.PrimaryVendor);
            Assert.AreEqual(input.SeasonName ?? string.Empty, output.SeasonName);
            Assert.AreEqual(input.TaxGroupCode ?? string.Empty, output.TaxGroupCode);
            Assert.AreEqual(input.TaxCategory ?? string.Empty, output.TaxCategory);
            Assert.AreEqual(input.BrandName ?? string.Empty, output.BrandName);
            Assert.AreEqual(true, output.Replenishment);
            Assert.AreEqual(input.CountryOfOrigin ?? string.Empty, output.CountryOfOrigin);
            Assert.AreEqual(input.CustomLongText1 ?? string.Empty, output.CustomLongText1);
            Assert.AreEqual(input.CustomLongText2 ?? string.Empty, output.CustomLongText2);
            Assert.AreEqual(input.CustomLongText3 ?? string.Empty, output.CustomLongText3);
            Assert.AreEqual(input.CustomLongText4 ?? string.Empty, output.CustomLongText4);
            Assert.AreEqual(input.CustomLongText5 ?? string.Empty, output.CustomLongText5);
            Assert.AreEqual(input.CustomLongText6 ?? string.Empty, output.CustomLongText6);
            Assert.AreEqual(string.Empty, output.CustomLongText7);
            Assert.AreEqual(string.Empty, output.CustomLongText8);
            Assert.AreEqual(string.Empty, output.CustomLongText9);
            Assert.AreEqual(string.Empty, output.CustomLongText10);
            Assert.AreEqual(string.Empty, output.CustomLongText11);
            Assert.AreEqual(string.Empty, output.CustomLongText12);
            Assert.AreEqual(string.Empty, output.Manufacturer);
            Assert.AreEqual(input.SubClass1.Substring(0, 1), output.Department);
            Assert.AreEqual(input.OrderCost, output.OrderCost);

            var item = output.Items.Single();

            Assert.AreEqual(6, item.WeeksOfSupply);
            Assert.AreEqual(input.EID, item.Eid);
            Assert.AreEqual(input.CLU, item.Clu);

            var upc = item.UPCs.Single();

            Assert.AreEqual(input.UPCValue, upc.Value);
            Assert.AreEqual(true, upc.IsDefault);

            Assert.AreEqual(input.Attribute1 ?? string.Empty, item.Attribute1);
            Assert.AreEqual(input.Attribute2 ?? string.Empty, item.Attribute2);

            Assert.AreEqual(input.Height ?? default(decimal), item.Height);
            Assert.AreEqual(input.Weight ?? default(decimal), item.Weight);
            Assert.AreEqual(input.Width ?? default(decimal), item.Width);
            Assert.AreEqual(input.Length ?? default(decimal), item.Length);

            Assert.AreEqual(input.ReleaseDate ?? null, item.ReleaseDate);

            Assert.AreEqual(false, item.NotTrackOh);
            Assert.AreEqual(true, item.TradeDiscount);
            Assert.AreEqual(true, item.MemberDiscount);
            Assert.AreEqual(false, item.Inactive);
            Assert.AreEqual(true, item.RequireDiscountAuthorizationCode);
            Assert.AreEqual(true, item.AcceptToken);
            Assert.AreEqual(true, item.AutoPromptToPayWithTokens);
            Assert.AreEqual(true, item.EligibleForLoyaltyRewards2);
            Assert.AreEqual(1, item.LoyaltyRewards2Ratio);

            Assert.AreEqual(input.ItemCost ?? default(decimal), item.OrderCost);
            Assert.AreEqual(input.CustomDate1 ?? null, item.CustomDate1);

            Assert.AreEqual(false, item.CustomFlag3);
            Assert.AreEqual(false, item.CustomFlag4);
            Assert.AreEqual(false, item.CustomFlag5);
            Assert.AreEqual(false, item.CustomFlag6);
            Assert.AreEqual(false, item.CustomFlag7);

            Assert.AreEqual(0, item.CustomNumber3);
            Assert.AreEqual(0, item.CustomNumber4);
            Assert.AreEqual(0, item.CustomNumber5);
            Assert.AreEqual(0, item.CustomNumber6);
            Assert.AreEqual(0, item.CustomNumber7);
            Assert.AreEqual(0, item.CustomNumber8);
            Assert.AreEqual(0, item.CustomNumber9);

            Assert.AreEqual(input.CustomText1 ?? string.Empty, item.CustomText1);
            Assert.AreEqual(input.CustomText2 ?? string.Empty, item.CustomText2);
            Assert.AreEqual(string.Empty, item.CustomText3);
            Assert.AreEqual(string.Empty, item.CustomText4);
            Assert.AreEqual(input.CustomText5 ?? string.Empty, item.CustomText5);
            Assert.AreEqual(string.Empty, item.CustomText6);
            Assert.AreEqual(string.Empty, item.CustomText7);
            Assert.AreEqual(string.Empty, item.CustomText8);
            Assert.AreEqual(input.CustomText9 ?? string.Empty, item.CustomText9);
            Assert.AreEqual(string.Empty, item.CustomText10);
            Assert.AreEqual(string.Empty, item.CustomText11);
            Assert.AreEqual(string.Empty, item.CustomText12);

            Assert.AreEqual(input.SubClass1 ?? string.Empty, item.SubClass1);
            Assert.AreEqual(input.SubClass2 ?? string.Empty, item.Subclass2);

            if (!string.IsNullOrWhiteSpace(item.SubClass1))
            {
                if (item.SubClass1.Length == 6)
                {
                    string elementClass = item.SubClass1.Substring(3, 3);

                    switch (item.SubClass1.Substring(0, 3).ToLowerInvariant())
                    {
                    case "p10":
                        elementClass = "1" + elementClass;
                        break;

                    case "m10":
                        elementClass = "2" + elementClass;
                        break;

                    case "g10":
                        elementClass = "3" + elementClass;
                        break;

                    case "f10":
                        elementClass = "6" + elementClass;
                        break;
                    }

                    Assert.AreEqual(elementClass, item.Class);
                }
            }

            Assert.AreEqual(input.BasePrice, item.BasePrice);
            this.ComparePricing(item.Prices, upc.Value, item.SubClass1, input.BasePrice);
        }
예제 #24
0
 //거래를 중단하고 삭제시킬때
 public void CancleTrade(TradeData data)
 {
     tradeDataList.Remove(data);
     Save();
 }
예제 #25
0
        /// <summary>
        /// Returns the most recent ShipShipTrade if update is succesful, null otherwise.
        /// Designed such that clients send trade data only when they attempt to update offered cargo. The result is pushed to both clients containing the latest update if it is succesful. This way, no polling necessary.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public ShipShipTrade UpdateTradeData(TradeData data)
        {
            lock (TRADELOCK)
            {
                ShipShipTrade trade;
                int           tradeId;
                if (!_shipIDToTradeID.TryGetValue(data.ShipID, out tradeId))
                {
                    return(null);
                }
                if (!_shipShipTrades.TryGetValue(tradeId, out trade))
                {
                    return(null);
                }

                CargoHandlerModel tradeCargo;
                CargoHandler_ReadOnlyVM <CargoHandlerModel> shipCargo;

                if (data.ShipID == trade.ShipA.Id)
                {
                    tradeCargo = trade.CargoOffered_A;
                    shipCargo  = trade.ShipA.GetCargo();
                }
                else if (data.ShipID == trade.ShipB.Id)
                {
                    tradeCargo = trade.CargoOffered_B;
                    shipCargo  = trade.ShipB.GetCargo();
                }
                else
                {
                    throw new CorruptStateException("TradeData id was not consistent with IDs stored in the retrieved ShipShipTrade object.");
                }

                trade.LastUpdateTime = TimeKeeper.MsSinceInitialization;

                var newStatefulCargo = new Dictionary <int, StatefulCargo>();
                foreach (var c in data.CargoData.StatefulCargo)
                {
                    //Check to make sure the ship holdss the cargo
                    var cargoType = shipCargo.IsCargoInHolds(c.Id);

                    if (cargoType != StatefulCargoTypes.Null)
                    {
                        if (cargoType != c.CargoType)
                        {
                            //Unlikely, but might as well check
                            throw new CorruptStateException("CargoType of cargo object sent with TradeData update did not match CargoType of StatefulCargo with the corresponding cargo ID.");
                        }

                        tradeCargo.StatefulCargo.Add(c.Id, shipCargo.GetStatefulCargo(c.Id));
                    }
                    else
                    {
                        return(null);//Cargo wasn't in holds, trade update fails.
                    }
                }
                tradeCargo.StatefulCargo = newStatefulCargo;

                var newStatelessCargo = new Dictionary <StatelessCargoTypes, StatelessCargo>();
                foreach (var c in data.CargoData.StatelessCargo)
                {
                    if (shipCargo.IsCargoInHolds(c.CargoType, c.Quantity))
                    {
                        newStatelessCargo.Add(c.CargoType, new StatelessCargo(c.CargoType, c.Quantity));
                    }
                    else
                    {
                        return(null);//Cargo wasn't in holds, trade update fails.
                    }
                }
                tradeCargo.StatelessCargo = newStatelessCargo;

                return(trade);
            }
        }
예제 #26
0
    ///// <summary> 거래 개수 추가 </summary>
    //public void AddTradeData()
    //{

    //    if (defaultDataCount <= tradeDataList.Count)
    //    {
    //        UIPopupManager.ShowInstantPopup("최대 거래 개수를 초과하셨습니다");
    //        return;
    //    }


    //    TradeData trade = new TradeData();
    //    tradeDataList.Add(trade);

    //    Save();
    //}

    //규칙에 따른 거래 데이터 구성
    void TradeDataSet()
    {
        int count = defaultDataCount;

        for (int i = 0; i < tradeDataList.Count; i++)
        {
            if (tradeDataList[i].isTrade)
            {
                count -= 1;
            }
        }

        if (count == 0)
        {
            return;
        }

        if (currentStorageList != null && currentStorageList.Count > 0)
        {
            currentStorageList.Clear();
        }

        if (Storage.storedItemDic.Count < 1)
        {
            return;
        }


        //현재 저장된 아이템 데이터 리스트를 가지고 새 리스트를 구성
        //currentStorageList = new List<ItemData>(TerritoryStorage.Instance.storageList);
        //currentStorageList = TerritoryStorage.Instance.storageList;


        currentStorageList = Storage.storedItemDic.Values.ToList();

        //저장량이 적은 순으로 정렬
        currentStorageList.Sort(delegate(Storage.StoredItemInfo dataA, Storage.StoredItemInfo dataB)
        {
            if (dataA.amount > dataB.amount)
            {
                return(1);
            }
            else if (dataA.amount < dataB.amount)
            {
                return(-1);
            }
            else
            {
                return(0);
            }
        });

        //산출 로직에 따른 아이디값 불러오기
        InitExportIDList();
        InitImportIDList();

        int listCount = defaultDataCount - tradeDataList.Count;

        for (int i = 0; i < listCount; i++)
        {
            int exportNum = Random.Range(0, exportIDList.Count);
            int importNum = Random.Range(0, importIDList.Count);

            if (exportIDList[exportNum] == importIDList[importNum])
            {
                i -= 1;
                continue;
            }
            else
            {
                TradeData trade = new TradeData();
                trade.sellMaterialID = exportIDList[exportNum];
                trade.buyMaterialID  = importIDList[importNum];
                tradeDataList.Add(trade);
            }
        }

        OnChangedTradeList();
    }
예제 #27
0
        /// <summary>
        /// 医保收费预算
        /// </summary>
        /// <param name="workid"></param>
        /// <param name="presList">处方数据</param>
        /// <param name="curPatList">病人对象</param>
        /// <param name="costPatTypeid">收费病人类型</param>
        /// <param name="diagnosisList">诊断信息</param>
        /// <param name="invoiceNO">发票号</param>
        /// <returns></returns>
        public static Dictionary <string, string> MIBalanceBuget(int workid, List <Prescription> presList, OP_PatList curPatList, int costPatTypeid, List <OPD_DiagnosisRecord> diagnosisList, string invoiceNO)
        {
            ResultClass resultClass = new ResultClass();
            string      sSocialCreateNumSocialCreateNum = string.Empty;

            resultClass = MIInterFaceFactory.Mz_GetRegisterTradeNo(curPatList.VisitNO);
            if (resultClass.bSucess)
            {
                sSocialCreateNumSocialCreateNum = resultClass.sRemarks;
            }
            else
            {
                throw new Exception("异常!" + resultClass.sRemarks);
            }
            InputClass input = new InputClass();
            Dictionary <InputType, object> dicStr = new Dictionary <InputType, object>();
            TradeData   tradeData   = new TradeData();
            Tradeinfo   tradeinfo   = new Tradeinfo();
            RecipeList  recipeList  = new RecipeList();
            FeeitemList feeitemList = new FeeitemList();

            tradeinfo.tradeType = TradeType.普通门诊;
            tradeinfo.billtype  = "0";
            tradeinfo.feeno     = invoiceNO;

            List <Recipe>       recipes           = new List <Recipe>();
            List <Feeitem>      feeitems          = new List <Feeitem>();
            int                 diagnoseCount     = diagnosisList.Count > 3 ? 3 : diagnosisList.Count;//最多取三条诊断
            List <Prescription> feeItemHeadIDList = GetPresHeadList(presList);

            for (int i = 0; i < diagnoseCount; i++)
            {
                int diagNo = i + 1;
                foreach (Prescription pres in feeItemHeadIDList)
                {
                    Recipe recipe = new Recipe();

                    recipe.diagnoseno      = diagNo.ToString();
                    recipe.recipeno        = pres.FeeItemHeadID.ToString();
                    recipe.recipedate      = DateTime.Now.ToString("yyyyMMddHHmmss");
                    recipe.drid            = "0999";
                    recipe.drname          = curPatList.RegDocName.ToString();
                    recipe.sectioncode     = curPatList.RegDeptID.ToString();
                    recipe.sectionname     = curPatList.RegDeptName.ToString();
                    recipe.hissectionname  = curPatList.RegDeptName.ToString();
                    recipe.diagnosecode    = diagnosisList[i].DiagnosisCode.Equals("")?"0000": diagnosisList[i].DiagnosisCode;
                    recipe.diagnosename    = diagnosisList[i].DiagnosisName;
                    recipe.registertradeno = sSocialCreateNumSocialCreateNum;
                    recipe.recipetype      = pres.IsReimbursement == 1?"2":"1";
                    if (pres.StatID == 100 || pres.StatID == 101)
                    {
                        recipe.billstype = "2";
                    }
                    else if (pres.StatID == 102)
                    {
                        recipe.billstype = "4";
                    }
                    else
                    {
                        recipe.billstype = "5";
                    }
                    recipes.Add(recipe);
                }
            }

            foreach (Prescription pres in presList)
            {
                if (pres.SubTotalFlag == 0 && pres.Selected == 1)
                {
                    Feeitem feeitem = new Feeitem();
                    feeitem.itemno   = pres.PresDetailID.ToString();// dr["PresDetailID"].ToString();
                    feeitem.recipeno = pres.FeeItemHeadID.ToString();
                    feeitem.hiscode  = pres.ItemID.ToString();
                    if (pres.StatID == 102)
                    {
                        feeitem.itemname      = "中药饮片及药材";
                        feeitem.specification = pres.ItemName.ToString().Trim();
                        feeitem.unitprice     = (pres.RetailPrice / pres.UnitNO).ToString("0.000");
                        feeitem.count         = (pres.TotalFee * pres.UnitNO / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
                        decimal totalfee = Convert.ToDecimal(feeitem.unitprice) * Convert.ToDecimal(feeitem.count);

                        feeitem.unit = pres.MiniUnit;
                        feeitem.days = pres.PresAmount.ToString();
                        feeitem.fee  = totalfee.ToString("0.00");

                        feeitem.packaging  = pres.MiniUnit;
                        feeitem.minpackage = pres.MiniUnit;
                        feeitem.conversion = "1";
                    }
                    else if (pres.ItemType.Equals("1"))
                    {
                        feeitem.itemname      = pres.ItemName.ToString().Trim();
                        feeitem.specification = pres.Spec.ToString();

                        feeitem.unitprice  = pres.RetailPrice.ToString("0.000");
                        feeitem.count      = (pres.TotalFee / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
                        feeitem.unit       = pres.PackUnit;
                        feeitem.days       = pres.Days.ToString();
                        feeitem.fee        = pres.TotalFee.ToString("0.00");
                        feeitem.packaging  = pres.PackUnit;
                        feeitem.minpackage = pres.DosageUnit;
                        feeitem.conversion = (Convert.ToDecimal(pres.Factor) * pres.UnitNO).ToString();
                        //待测试的
                        //feeitem.unitprice = (pres.RetailPrice / pres.UnitNO).ToString("0.000");
                        //feeitem.count = (pres.TotalFee * pres.UnitNO / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
                        //decimal totalfee = Convert.ToDecimal(feeitem.unitprice) * Convert.ToDecimal(feeitem.count);

                        //feeitem.unit = pres.MiniUnit;
                        //feeitem.days = pres.Days.ToString();
                        //feeitem.fee = totalfee.ToString("0.00");
                    }
                    else
                    {
                        feeitem.itemname      = pres.ItemName.ToString().Trim();
                        feeitem.specification = pres.Spec.ToString();

                        feeitem.unitprice  = pres.RetailPrice.ToString("0.000");
                        feeitem.count      = (pres.TotalFee / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
                        feeitem.unit       = pres.PackUnit;
                        feeitem.days       = pres.Days.ToString();
                        feeitem.fee        = pres.TotalFee.ToString("0.00");
                        feeitem.packaging  = feeitem.unit;
                        feeitem.minpackage = feeitem.unit;
                        feeitem.conversion = "1";
                        //待测试的
                        //feeitem.unitprice = (pres.RetailPrice / pres.UnitNO).ToString("0.000");
                        //feeitem.count = (pres.TotalFee * pres.UnitNO / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
                        //decimal totalfee = Convert.ToDecimal(feeitem.unitprice) * Convert.ToDecimal(feeitem.count);

                        //feeitem.unit = pres.MiniUnit;
                        //feeitem.days = pres.Days.ToString();
                        //feeitem.fee = totalfee.ToString("0.00");
                    }

                    feeitem.itemtype = Convert.ToInt32(pres.ItemType) == Convert.ToInt32(OP_Enum.ItemType.药品) ? "0" : "1";

                    feeitem.babyflag = "0";

                    feeitem.dosage = pres.Dosage.ToString();
                    feeitem.dose   = pres.DosageId.ToString();

                    feeitem.howtouse = pres.FrequencyID.ToString();//"02";//pres.FrequencyName;


                    if (feeitem.itemtype == "0")
                    {
                        feeitem.drugapprovalnumber = pres.DrugApprovalnumber;
                    }
                    else
                    {
                        feeitem.drugapprovalnumber = string.Empty;
                    }
                    feeitems.Add(feeitem);
                }
            }
            feeitemList.feeitems = feeitems;
            recipeList.recipes   = recipes;
            #region 新版,诊断分类型增加
            //List<Recipe> recipes = new List<Recipe>();
            //List<Feeitem> feeitems = new List<Feeitem>();
            ////1按项目类型分类
            //var fL = from item in presList
            //         group item by new { item.ItemType } into g
            //        select new
            //        {
            //            ItemType = g.Key.ItemType
            //        };
            //int recCount = 0;
            ////2.分类型插入诊断和项目
            //foreach (var f in fL)
            //{
            //    //2.1添加诊断
            //    Recipe recipe = new Recipe();
            //    recipe.diagnoseno = recCount.ToString();
            //    recipe.recipeno = recCount.ToString();
            //    recipe.recipedate = DateTime.Now.ToString("yyyyMMddHHmmss");
            //    recipe.drid = "0999";//curPatList.RegEmpID.ToString();
            //    recipe.drname = curPatList.RegDocName.ToString();
            //    recipe.sectioncode = curPatList.RegDeptID.ToString();
            //    recipe.sectionname = curPatList.RegDeptName.ToString();
            //    recipe.hissectionname = curPatList.RegDeptName.ToString();
            //    recipe.diagnosecode = curPatList.DiseaseCode;
            //    recipe.diagnosename = curPatList.DiseaseName;
            //    recipe.registertradeno = sSocialCreateNumSocialCreateNum;
            //    recipe.billstype = f.ItemType.Equals("1") ? "2" : "5";
            //    recipes.Add(recipe);

            //    //2.2添加明细
            //    List<Prescription> PrescriptionList = presList.FindAll(x => x.ItemType == f.ItemType);
            //    foreach (Prescription pres in PrescriptionList)
            //    {
            //        if (pres.SubTotalFlag == 0 && pres.Selected == 1)
            //        {
            //            Feeitem feeitem = new Feeitem();
            //            feeitem.itemno = pres.PresDetailID.ToString();// dr["PresDetailID"].ToString();
            //            feeitem.recipeno = recCount.ToString();//pres.FeeItemHeadID.ToString();
            //            feeitem.hiscode = pres.ItemID.ToString();
            //            feeitem.itemname = pres.ItemName.ToString().Trim();
            //            feeitem.itemtype = Convert.ToInt32(pres.ItemType) == Convert.ToInt32(OP_Enum.ItemType.药品) ? "0" : "1";
            //            feeitem.unitprice = pres.RetailPrice.ToString("0.000");
            //            feeitem.count = (pres.TotalFee / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
            //            feeitem.fee = pres.TotalFee.ToString("0.00");
            //            feeitem.babyflag = "0";

            //            feeitem.dosage = pres.Dosage;
            //            feeitem.dose = pres.DosageName;
            //            feeitem.days = pres.Days.ToString();
            //            feeitem.howtouse = pres.FrequencyName;
            //            feeitem.specification = pres.Spec;
            //            feeitem.unit = pres.MiniUnit;


            //            if (feeitem.itemtype == "0")
            //            {
            //                feeitem.drugapprovalnumber = pres.DrugApprovalnumber;
            //            }
            //            else
            //            {
            //                feeitem.drugapprovalnumber = string.Empty;
            //            }
            //            feeitems.Add(feeitem);
            //        }
            //    }

            //    recCount += 1;
            //}
            //recipeList.recipes = recipes;
            //feeitemList.feeitems = feeitems;
            #endregion

            #region 老版,只传一个诊断
            //List<Recipe> recipes = new List<Recipe>();
            //Recipe recipe = new Recipe();
            //recipe.diagnoseno = "1";
            //recipe.recipeno = "1";
            //recipe.recipedate = DateTime.Now.ToString("yyyyMMddHHmmss");
            //recipe.drid = "0999";//curPatList.RegEmpID.ToString();
            //recipe.drname = curPatList.RegDocName.ToString();
            //recipe.sectioncode = curPatList.RegDeptID.ToString();
            //recipe.sectionname = curPatList.RegDeptName.ToString();
            //recipe.hissectionname = curPatList.RegDeptName.ToString();
            //recipe.diagnosecode = curPatList.DiseaseCode;
            //recipe.diagnosename = curPatList.DiseaseName;
            //recipe.registertradeno = string.Empty;
            //recipes.Add(recipe);
            //recipeList.recipes = recipes;

            //List<Feeitem> feeitems = new List<Feeitem>();
            //foreach (Prescription pres in presList)
            //{
            //    if (pres.SubTotalFlag == 0 && pres.Selected==1)
            //    {
            //        Feeitem feeitem = new Feeitem();
            //        feeitem.itemno = pres.PresDetailID.ToString();// dr["PresDetailID"].ToString();
            //        feeitem.recipeno = "1";//pres.FeeItemHeadID.ToString();
            //        feeitem.hiscode = pres.ItemID.ToString();
            //        feeitem.itemname = pres.ItemName.ToString().Trim();
            //        feeitem.itemtype = Convert.ToInt32(pres.ItemType) == Convert.ToInt32(OP_Enum.ItemType.药品) ? "0" : "1";
            //        feeitem.unitprice = pres.RetailPrice.ToString("0.000");
            //        feeitem.count = (pres.TotalFee / pres.RetailPrice).ToString("0.00"); //pres.Amount.ToString();
            //        feeitem.fee = pres.TotalFee.ToString("0.00");
            //        feeitem.babyflag = "0";

            //        if (feeitem.itemtype == "0")
            //        {
            //            feeitem.drugapprovalnumber = pres.DrugApprovalnumber;
            //        }
            //        else
            //        {
            //            feeitem.drugapprovalnumber = string.Empty;
            //        }
            //        feeitems.Add(feeitem);
            //    }
            //}
            //feeitemList.feeitems = feeitems;
            #endregion

            tradeData.MIID     = costPatTypeid;
            tradeData.SerialNo = curPatList.VisitNO;

            tradeData.tradeinfo   = tradeinfo;
            tradeData.recipeList  = recipeList;
            tradeData.feeitemList = feeitemList;

            dicStr.Add(InputType.TradeData, JsonHelper.SerializeObject(tradeData));
            dicStr.Add(InputType.bFlag, true);
            input.SInput = dicStr;
            resultClass  = MIInterFaceFactory.MZ_PreviewCharge(input);
            if (resultClass.bSucess)
            {
                Dictionary <string, string> resultDic = (Dictionary <string, string>)resultClass.oResult;
                Dictionary <string, string> myDic     = new Dictionary <string, string>();
                myDic.Add("ID", resultDic["Id"]);//医保预结算ID
                decimal medicarepay = Convert.ToDecimal(resultDic["fund"]) + Convert.ToDecimal(resultDic["personcountpay"]);
                myDic.Add("MedicarePay", medicarepay.ToString("0.00"));
                myDic.Add("MedicareMIPay", Convert.ToDecimal(resultDic["fund"]).ToString("0.00"));
                myDic.Add("MedicarePersPay", Convert.ToDecimal(resultDic["personcountpay"]).ToString("0.00"));
                StringBuilder strBuild = new StringBuilder();
                strBuild.Append("统筹支付:" + Convert.ToDecimal(resultDic["fund"]).ToString("0.00") + " ");
                strBuild.Append("现金支付:" + Convert.ToDecimal(resultDic["cash"]).ToString("0.00") + " ");
                strBuild.Append("个帐支付:" + Convert.ToDecimal(resultDic["personcountpay"]).ToString("0.00") + " ");
                myDic.Add("MedicardInfo", strBuild.ToString());
                if (!resultClass.sRemarks.Equals(""))
                {
                    MessageBox.Show("警告:" + resultClass.sRemarks);
                }
                return(myDic);
            }
            else
            {
                throw new Exception("异常!" + resultClass.sRemarks);
            }
        }
예제 #28
0
        /// <summary>
        /// 处理订单完成时的相应逻辑
        /// </summary>
        public void Start()
        {
            //获取店铺的基础数据
            ShopData data = new ShopData();
            ShopInfo shop = data.ShopInfoGetByNick(TradeInfo.Nick);

            //Console.Write(shop.Session + "!!!!!!!!!!!!\r\n");
            if (shop.Version != "2" && shop.Version != "3")
            {
                return;
            }

            //通过TOP接口查询该订单的详细数据并记录到数据库中
            TopApiHaoping api       = new TopApiHaoping(shop.Session);
            TradeData     tradeData = new TradeData();
            Trade         trade     = tradeData.GetTradeDetailShippingInfo(TradeInfo);

            trade = api.GetTradeByTid(trade);

            //记录该订单对应的评价记录
            TradeRate tradeRate = api.GetTradeRate(trade);

            tradeRate.ItemId = trade.NumIid;
            tradeRate.Nick   = TradeInfo.Nick;

            //只有双方都评价了才会有插入数据库和赠送的操作
            if (tradeRate.Content != "")
            {
                //判断该订单是否已经有过评价记录
                TradeRateData dbTradeRate = new TradeRateData();
                if (!dbTradeRate.CheckTradeRateExits(tradeRate))
                {
                    //没有记录过写入数据库
                    dbTradeRate.InsertTradeInfo(tradeRate);
                }

                //判断该订单是否存在
                TradeData dbTrade = new TradeData();
                if (!dbTrade.CheckTradeExits(trade))
                {
                    //更新该订单的评价时间
                    dbTrade.InsertTradeInfo(trade);
                }

                //更新该订单的评价时间
                dbTrade.UpdateTradeRateById(trade, tradeRate);
            }
            else
            {
                //否则中断
                return;
            }

            //判断如果是分销的订单,则不处理
            if (trade.OrderType.ToLower() == "fenxiao")
            {
                return;
            }

            try
            {
                //更新订单的优惠券使用情况
                TopApiHaoping apiCoupon = new TopApiHaoping(shop.Session);
                string        result    = apiCoupon.GetCouponTradeTotalByNick(trade);

                MatchCollection match = new Regex(@"<promotion_details list=""true""><promotion_detail><discount_fee>([^\<]*)</discount_fee><id>[0-9]*</id><promotion_desc>[^\<]*</promotion_desc><promotion_id>shopbonus-[0-9]*_[0-9]*-([0-9]*)</promotion_id><promotion_name>店铺优惠券</promotion_name></promotion_detail>", RegexOptions.IgnoreCase).Matches(result);

                if (match.Count != 0)
                {
                    string price    = match[0].Groups[1].ToString();
                    string couponid = match[0].Groups[2].ToString();

                    if (couponid.Length != 0)
                    {
                        TradeData dataTradeCoupon = new TradeData();
                        dataTradeCoupon.UpdateTradeCouponInfo(trade, price, couponid);
                    }
                }
            }
            catch { }

            //判断是否开启了客服审核,如果开启了则自动记录并中断
            if (shop.IsKefu == "1")
            {
                TradeRateData dataKefu   = new TradeRateData();
                string        resultKefu = "手动审核订单!";
                dataKefu.UpdateTradeRateResult(tradeRate, resultKefu);

                //更新该订单的评价为待审核状态
                TradeData dbTrade = new TradeData();
                if (!dbTrade.CheckTradeRateCheckExits(trade))
                {
                    dbTrade.UpdateTradeKefuById(trade, tradeRate);
                }

                try
                {
                    //记录会员信息数据
                    GetUserData getUser = new GetUserData();
                    getUser.Get(trade);
                }
                catch { }

                return;
            }

            Console.WriteLine(trade.ShippingType + "!!");

            //获取订单的具体物流状态,如果订单物流状态为空则获取物流信息
            if (trade.ShippingType != "system" && trade.ShippingType != "self")
            {
                //获取该订单的物流状态
                TopApiHaoping apiHaoping = new TopApiHaoping(shop.Session);
                string        status     = apiHaoping.GetShippingStatusByTid(trade);
                TradeData     dbTrade    = new TradeData();

                Console.Write(status + "\r\n");
                //如果该物流信息不存在
                if (status.IndexOf("不存在") != -1)
                {
                    //如果该物流公司不支持查询则更新为self
                    dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                }

                //获取该订单的物流相关信息
                trade = api.GetOrderShippingInfo(trade);
                if (!dbTrade.IsTaobaoCompany(trade))
                {
                    //如果不是淘宝合作物流则直接更新
                    dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                    trade.ShippingType = "self";
                }
                else
                {
                    //根据服务器的物流状态进行判断,如果物流状态是已签收
                    if (status == "ACCEPTED_BY_RECEIVER" || status == "ACCEPTING" || status == "ACCEPTED")
                    {
                        string result = api.GetShippingStatusDetailByTid(trade);
                        Console.Write("【" + result + "】\r\n");
                        //如果是虚拟物品
                        if (result.IndexOf("该订单未指定运单号") != -1)
                        {
                            //如果该物流公司不支持查询则更新为self
                            dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                        }

                        //如果订单不是服务器错误
                        if (result.IndexOf("company-not-support") != -1)
                        {
                            //如果该物流公司不支持查询则更新为self
                            dbTrade.UpdateTradeShippingStatusSelf(trade, status);
                        }

                        //再根据订单的详细物流信息判断签收的状态
                        if (result.IndexOf("签收人") != -1 || result.IndexOf(" 妥投") != -1 || result.IndexOf(" 签收") != -1 || result.IndexOf("正常签收") != -1 || result.IndexOf(" 已签收") != -1)
                        {
                            //如果物流已经签收了则更新对应订单状态
                            trade.DeliveryEnd  = utils.GetShippingEndTime(result);;
                            trade.DeliveryMsg  = result;
                            trade.ShippingType = "system";

                            //如果物流到货时间还是为空
                            if (trade.DeliveryEnd == "")
                            {
                                LogData dbLog = new LogData();
                                dbLog.InsertErrorLog(trade.Nick, "deliveryDateNullOrder", "", result, "");
                            }

                            dbTrade.UpdateTradeShippingStatusSystem(trade, status);
                        }
                    }
                }
            }

            //处理优惠券赠送及短信-上LOCK锁定
            lock (TradeSuccess.padlockRate)
            {
                //淘宝优惠券赠送
                bool isSendCoupon = true;
                //判断是否符合赠送条件
                if (CheckCouponSend(shop, tradeRate, trade))
                {
                    //如果符合赠送条件调用赠送接口
                    CouponData dbCoupon = new CouponData();
                    Coupon     coupon   = dbCoupon.GetCouponInfoById(shop);

                    //判定该优惠券是否过期或删除
                    if (!dbCoupon.CheckCouponCanUsed(shop))
                    {
                        //优惠券过期,自动帮客户延长优惠券期限
                        //考虑到淘宝即将开启短授权,该功能改成消息通知,暂不制作
                        isSendCoupon = false;
                        //return;
                    }
                    else
                    {
                        //解决多线程冲突问题先插入优惠券赠送记录,如果赠送失败再删除记录
                        string couponId = string.Empty;
                        if (dbCoupon.InsertCouponSendRecord(trade, shop, couponId))
                        {
                            string taobaoResult = string.Empty;
                            couponId = api.SendCoupon(trade.BuyNick, coupon.TaobaoCouponId, ref taobaoResult);

                            //获取的赠送接口的返回结果
                            if (couponId != "")
                            {
                                //如果成功赠送则记录
                                dbCoupon.UpdateCouponSendRecord(trade, shop, couponId);
                            }
                            else
                            {
                                //如果没有赠送成功则删除刚才的临时记录
                                dbCoupon.DeleteCouponSendRecord(trade, shop, couponId);
                                Console.WriteLine(couponId);
                                try
                                {
                                    //记录淘宝自身错误
                                    string        err      = new Regex(@"<reason>([^<]*)</reason>", RegexOptions.IgnoreCase).Match(taobaoResult).Groups[1].ToString();
                                    TradeRateData dataRate = new TradeRateData();
                                    if (err.Length == 0)
                                    {
                                        taobaoResult += "淘宝系统错误,不赠送优惠券,错误代码是【" + taobaoResult + "】!";
                                    }
                                    else
                                    {
                                        taobaoResult += "淘宝系统错误,不赠送优惠券,错误代码是【" + err + "】!";
                                    }
                                    dataRate.UpdateTradeRateResult(tradeRate, taobaoResult);
                                }
                                catch { }
                                //有可能是客户订购的优惠券服务已经到期记录错误信息并中断
                                //return;
                                isSendCoupon = false;
                            }
                        }
                        else
                        {
                            isSendCoupon = false;
                        }
                    }
                }
                else
                {
                    isSendCoupon = false;
                }

                //支付宝现金券赠送
                bool isSendAlipay = true;
                //判断是否符合赠送条件
                if (CheckAlipaySend(shop, tradeRate, trade))
                {
                    //获取一条需要赠送的支付宝红包数据
                    CouponData   cou    = new CouponData();
                    AlipayDetail detail = cou.GetAlipayDetailInfoById(shop);

                    //如果符合赠送条件调用短信接口直接将红包发到客户手机上
                    string shopName = shop.MsgShopName;
                    if (shop.MsgShopName.Length == 0)
                    {
                        shopName = shop.Nick;
                    }
                    string msgAlipay = "亲," + shopName + "赠送您支付宝红包,卡号" + detail.Card + "密码" + detail.Pass + ",您可以到支付宝绑定使用。";
                    Console.Write(msgAlipay + "\r\n");
                    string msgResultAlipay = Message.Send(trade.Mobile, msgAlipay);

                    Console.Write(msgResultAlipay + "\r\n");
                    //更新支付宝红包使用状态
                    cou.InsertAlipaySendRecord(trade, shop, detail);

                    //记录短信发送记录
                    ShopData dbAlipay = new ShopData();
                    if (msgResultAlipay != "0")
                    {
                        dbAlipay.InsertShopMsgLog(shop, trade, msgAlipay, msgResultAlipay, "alipay");
                    }
                    else
                    {
                        isSendAlipay = false;
                        dbAlipay.InsertShopErrMsgLog(shop, trade, msgAlipay, msgResultAlipay, "alipay");
                    }
                    shop.MsgCount = (int.Parse(shop.MsgCount) - 1).ToString();
                }
                else
                {
                    isSendAlipay = false;
                }

                //包邮卡赠送
                bool isSendFreeCard = true;
                try
                {
                    //判断是否符合赠送条件
                    if (CheckFreeCardSend(shop, tradeRate, trade))
                    {
                        //赠送包邮卡
                        FreeCardData freeData = new FreeCardData();
                        freeData.SendFreeCard(shop, trade);

                        //判断该用户是否开启了包邮卡短信
                        if (shop.MsgIsFreecard == "1" && int.Parse(shop.MsgCount) > 0)
                        {
                            ShopData db   = new ShopData();
                            FreeCard free = freeData.GetFreeCardById(shop.FreeCardId);
                            //发送短信
                            string msg = Message.GetMsg(shop.MsgFreecardContent, shop.MsgShopName, TradeInfo.BuyNick, shop.IsCoupon, free.Name);

                            //手机号码为空不发
                            if (trade.Mobile.Length == 0)
                            {
                                return;
                            }

                            if (!db.IsSendMsgToday(trade, "freecard"))
                            {
                                string msgResult = Message.Send(trade.Mobile, msg);

                                //记录
                                if (msgResult != "0")
                                {
                                    db.InsertShopMsgLog(shop, trade, msg, msgResult, "freecard");
                                }
                                else
                                {
                                    db.InsertShopErrMsgLog(shop, trade, msg, msgResult, "freecard");
                                }
                                shop.MsgCount = (int.Parse(shop.MsgCount) - 1).ToString();
                            }
                        }
                    }
                    else
                    {
                        isSendFreeCard = false;
                    }
                }
                catch (Exception e) {
                    Console.WriteLine(e.Message + e.StackTrace + e.Source);
                }



                try
                {
                    //记录会员信息数据
                    GetUserData getUser = new GetUserData();
                    getUser.Get(trade);
                }
                catch { }

                //Console.WriteLine(isSendCoupon + "!!");
                //Console.WriteLine(isSendAlipay + "!!");
                //Console.WriteLine(trade.Mobile + "!!");

                //如果优惠券和支付宝现金都没有赠送成功,则直接中断方法不发短信
                //2012.9.17改为只有赠送成功优惠券才发送此短信
                if (!isSendCoupon)
                {
                    return;
                }

                //判断该用户是否开启了发货短信
                if (shop.MsgIsCoupon == "1" && int.Parse(shop.MsgCount) > 0)
                {
                    ShopData db = new ShopData();
                    //发送短信
                    string msg = Message.GetMsg(shop.MsgCouponContent, shop.MsgShopName, TradeInfo.BuyNick, shop.IsCoupon);
                    //string msg = Message.GetMsg(shop, trade, shop.MsgCouponContent);

                    //手机号码为空不发
                    if (trade.Mobile.Length == 0)
                    {
                        return;
                    }

                    if (!db.IsSendMsgToday(trade, "gift"))
                    {
                        ////先插入数据库 解决多优惠券赠送短信多发问题
                        //db.InsertShopMsgLog(shop, trade, msg, "888888", "gift");

                        string msgResult = Message.Send(trade.Mobile, msg);

                        //记录
                        if (msgResult != "0")
                        {
                            db.InsertShopMsgLog(shop, trade, msg, msgResult, "gift");
                        }
                        else
                        {
                            db.InsertShopErrMsgLog(shop, trade, msg, msgResult, "gift");
                        }
                        shop.MsgCount = (int.Parse(shop.MsgCount) - 1).ToString();
                    }
                }
            }
        }
예제 #29
0
        public static void HistTradeRequest(string traderName, string companyName, string brokerName,
                                            string instrumentName, string commodityName, string firstSeqName, 
                                            DateTime fromDate, DateTime toDate)
        {
            int nrFilter = 0;
            MarketDataRequest request;
            request = new MarketDataRequest();

            // @@@ filter inputs for reasonable values, i.e. warning for many days etc...

            request.DataType = MarketDataTypeEnum.Deals;
            request.FilterRules = new FilterRule[
                                        (traderName == "All"? 0 : 1) +
                                        (companyName == "All"? 0 : 1) +
                                        (brokerName == "All"? 1 : 1) +
                                        (instrumentName == "All" && commodityName == "All"? 0 : 1) +
                                        (firstSeqName == "All" ? 0 : 1) +
                                        + 1]; // +1 Dates// @@@ how to filter for gas as commodity

            // Date Filter
            DateFilterRule dateFilter = new DateFilterRule();
            dateFilter.StartDate = fromDate;
            dateFilter.EndDate = toDate;
            request.FilterRules[nrFilter] = dateFilter; nrFilter+=1;

            // Trader Filter
            if(traderName != "All")
            {
                TraderNameFilterRule traderFilter = new TraderNameFilterRule();
                traderFilter.Action = FilterRuleActionEnum.Add;
                traderFilter.TraderName = traderName;
                request.FilterRules[nrFilter] = traderFilter; nrFilter += 1;
            }

            // Instrument Filter == Product, e.g. NBP, not tenor!
            // We introduced Commodity which is a collection of intruments; setting an Instrument Type will supersede the Commodity
            if (instrumentName != "All")
            {
                InstrumentsFilterRule instrumentsFilter = new InstrumentsFilterRule();
                InstrumentFilterRule[] iGroup = new InstrumentFilterRule[1]; // @@@ extend >1 later

                InstrumentFilterRule iRule = new InstrumentFilterRule();
                iRule.Action = FilterRuleActionEnum.Add;
                iRule.InstrumentName = instrumentName;
                iGroup[0] = iRule;

                instrumentsFilter.InstrumentRules = iGroup;
                request.FilterRules[nrFilter] = instrumentsFilter; nrFilter += 1;
            }
            else if (commodityName != "All")
            {
                List<string> _instNames;
                if (CommodityGrouper.CommodityClassList.Contains(commodityName))
                {
                    _instNames = TP_SetupData.Commodities.Values.Where(k => k.CommodityClass == commodityName).Select(k => k.InstName).ToList();
                }
                else if (CommodityGrouper.CommodityList.Contains(commodityName))
                {
                    _instNames = TP_SetupData.Commodities.Values.Where(k => k.Commodity == commodityName).Select(k => k.InstName).ToList();
                }
                else
                {
                    throw new ArgumentOutOfRangeException("Commodity = " + commodityName + " unknown.");
                }

                InstrumentsFilterRule instrumentsFilter = new InstrumentsFilterRule();
                InstrumentFilterRule[] iGroup = new InstrumentFilterRule[_instNames.Count];

                InstrumentFilterRule iRule;
                for (int i = 0; i < _instNames.Count; i++)
                {
                    iRule = new InstrumentFilterRule();
                    iRule.Action = FilterRuleActionEnum.Add;
                    iRule.InstrumentName = _instNames[i];
                    iGroup[i] = iRule;
                }

                instrumentsFilter.InstrumentRules = iGroup;
                request.FilterRules[nrFilter] = instrumentsFilter; nrFilter += 1;
            }

            // FirstSqeuenceName Filter, e.g. Sep-16, Win 16-17, ...
            if (firstSeqName != "All")
            {
                SequenceFilterRule iRule = new SequenceFilterRule(); // multiple not possible
                iRule.Action = FilterRuleActionEnum.Add;
                iRule.SequenceItemName = firstSeqName;

                request.FilterRules[nrFilter] = iRule; nrFilter += 1;
            }

            // Company Filter
            if (companyName != "All")
            {
                CompaniesFilterRule companiesFilter = new CompaniesFilterRule();
                CompanyFilterRule[] cGroup = new CompanyFilterRule[1]; // @@@ extend >1 later (possible?)

                CompanyFilterRule cRule = new CompanyFilterRule();
                cRule.Action = FilterRuleActionEnum.Add;
                cRule.CompanyName = companyName;
                cGroup[0] = cRule;

                companiesFilter.CompanyRules = cGroup;
                request.FilterRules[nrFilter] = companiesFilter; nrFilter += 1;
            }

            // Broker Filter
            BrokersFilterRule brokersFilter= new BrokersFilterRule();
            BrokerFilterRule[] bGroup;
            BrokerFilterRule bRule;

            if (brokerName == "All")
            {
                //char[] firstLetters = "SPI".ToCharArray();
                //bGroup = new BrokerFilterRule[firstLetters.Length];
                //for (int i = 0; i < firstLetters.Length; i++)
                //{
                //    bRule = new BrokerFilterRule();
                //    bRule.Action = FilterRuleActionEnum.Add;
                //    bRule.CombineBrokers = true;
                //    bRule.BrokerName = firstLetters[i].ToString();
                //    bGroup[i] = bRule;
                //}

                bGroup = new BrokerFilterRule[1];
                bRule = new BrokerFilterRule();
                bRule.Action = FilterRuleActionEnum.Add;
                bRule.CombineBrokers = true;
                bRule.BrokerName = "";
                bGroup[0] = bRule;
            }
            else
            {
                bGroup = new BrokerFilterRule[1];
                bRule = new BrokerFilterRule();
                bRule.Action = FilterRuleActionEnum.Add;
                bRule.CombineBrokers = true;
                bRule.BrokerName = brokerName;
                bGroup[0] = bRule;
            }

            brokersFilter.BrokerRules = bGroup;
            request.FilterRules[nrFilter] = brokersFilter; nrFilter += 1;

            DealsServiceSoapClient api = new DealsServiceSoapClient();
            MarketDataResponse response = api.GetDeals(request);
            Debugger.AddDebugLine("Query executed.");

            // convert data into our structure
            Deal[] deals =  response.Deals.Deals;

            GV8APIDATA data = new GV8APIDATA();
            data.TRADE = new TradeData[deals.Length];
            for(int i = 0; i < deals.Length; i++)
            {
                TradeData tpDeal = new TradeData();
                TrayportDeal srcDeal = (TrayportDeal)deals[i];

                tpDeal.TradeID = srcDeal.DealId;
                tpDeal.DateTime = srcDeal.DealDate; tpDeal._DateTime = tpDeal.DateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                tpDeal.Price = srcDeal.Price;
                tpDeal.Volume = srcDeal.Quantity;
                tpDeal.INSTSPECIFIER = new InstspecifierData();
                tpDeal.INSTSPECIFIER.InstID = srcDeal.InstrumentId;
                tpDeal.INSTSPECIFIER.InstName = srcDeal.InstrumentName;
                tpDeal.INSTSPECIFIER.FirstSequenceID = srcDeal.FirstSequenceId;
                tpDeal.INSTSPECIFIER.FirstSequenceItemName = srcDeal.FirstSequenceItemName;
                tpDeal.INSTSPECIFIER.SecondSequenceItemName = srcDeal.SecondSequenceItemName;
                tpDeal.InitiatorCompany = srcDeal.InitiatorCompany; //@@@ name or ID? check
                tpDeal.InitiatorBroker = srcDeal.InitiatorBroker; // @@@
                tpDeal.InitiatorTrader= srcDeal.InitiatorTrader; // @@@
                tpDeal.InitiatorAction = srcDeal.InitiatorAction; // @@@
                tpDeal.AggressorCompany = srcDeal.AggressorCompany; //@@@
                tpDeal.AggressorBroker = srcDeal.AggressorBroker; // @@@
                tpDeal.AggressorTrader = srcDeal.AggressorTrader; // @@@
                tpDeal.AggressorAction = srcDeal.AggressorAction; // @@@
                tpDeal.LastUpdate = srcDeal.LastUpdate; tpDeal._LastUpdate = tpDeal.LastUpdate.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
                tpDeal.InitiatorUser = srcDeal.InitiatorUser; //@@@
                tpDeal.AggressorUser = srcDeal.AggressorUser; //@@@

                tpDeal.ManualDeal = srcDeal.ManualDeal.HasValue? srcDeal.ManualDeal.Value : false;
                tpDeal._ManualDeal = srcDeal.ManualDeal.HasValue ? srcDeal.ManualDeal.Value.ToString() : null;
                tpDeal.VoiceDeal = srcDeal.VoiceDeal.HasValue ? srcDeal.VoiceDeal.Value : false;
                tpDeal._VoiceDeal = srcDeal.VoiceDeal.HasValue ? srcDeal.VoiceDeal.Value.ToString() : null;
                tpDeal.InitSleeve = srcDeal.InitSleeve.HasValue ? srcDeal.InitSleeve.Value : false;
                tpDeal._InitSleeve = srcDeal.InitSleeve.HasValue ? srcDeal.InitSleeve.Value.ToString() : null;
                tpDeal.AggSleeve = srcDeal.AggSleeve.HasValue ? srcDeal.AggSleeve.Value : false;
                tpDeal._AggSleeve = srcDeal.AggSleeve.HasValue ? srcDeal.AggSleeve.Value.ToString() : null;
                tpDeal.PNC = srcDeal.PNC.HasValue ? srcDeal.PNC.Value : false;
                tpDeal._PNC = srcDeal.PNC.HasValue ? srcDeal.PNC.Value.ToString() : null;

                /* 3 more  I cannot find in the normal TP responses for current trades:
                * tpDeal.INSTSPECIFIER.e = srcDeal.ExchangeDealId.HasValue ? srcDeal.ExchangeDealId.Value : 0;
                * private string sCoTAOriginField;
                * private string sCoTADeliveryPointField;
                */
                data.TRADE[i] = tpDeal;
            }

            Adaptor.HistTrades = data;
            string name = "HistTrades";
            Trayport_API.XmlHandler.Save2Data(XmlHandler.SerializeToXml(request).OuterXml, name + ".query");

            // @@@skip writing? excessive ....
            //Trayport_API.XmlHandler.Save2Data(XmlHandler.SerializeToXml(data).OuterXml, name + ".data");
        }
예제 #30
0
 static void ClearAcceptTradeMode(TradeData myTrade, TradeData hisTrade)
 {
     myTrade.SetInAcceptProcess(false);
     hisTrade.SetInAcceptProcess(false);
 }
예제 #31
0
        public static void HandleAcceptTradeOpcode(ref PacketReader packet, ref WorldManager manager)
        {
            Player    player     = manager.Character;
            Player    trader     = manager.Character.TradeInfo.Trader;
            TradeData thistrade  = manager.Character.TradeInfo;
            TradeData othertrade = manager.Character.TradeInfo.TraderData;

            Item[] myitems    = new Item[TradeData.TRADE_SLOT_COUNT];
            Item[] otheritems = new Item[TradeData.TRADE_SLOT_COUNT];

            thistrade.SetAccepted(true);

            if (thistrade.Money > player.Money)
            {
                ChatManager.Instance.SendNotification(player, "You do not have enough gold");
                return;
            }

            if (othertrade.Money > trader.Money)
            {
                ChatManager.Instance.SendNotification(trader, "You do not have enough gold");
                return;
            }

            for (byte i = 0; i < TradeData.TRADE_SLOT_COUNT; i++)
            {
                if (thistrade.GetItem(i)?.IsSoulbound == true)
                {
                    player.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                    trader.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                    return;
                }

                if (othertrade.GetItem(i)?.IsSoulbound == true)
                {
                    player.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                    trader.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                    return;
                }
            }

            if (othertrade.Accepted)
            {
                //TODO spell cast checks

                //Inventory checks
                for (byte i = 0; i < TradeData.TRADE_SLOT_COUNT; i++)
                {
                    if (othertrade.GetItem(i) != null)
                    {
                        if (!trader.Inventory.CanStoreItem(othertrade.GetItem(i).Entry, othertrade.GetItem(i).StackCount))
                        {
                            player.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                            trader.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                            return;
                        }
                    }

                    if (thistrade.GetItem(i) != null)
                    {
                        if (!player.Inventory.CanStoreItem(thistrade.GetItem(i).Entry, thistrade.GetItem(i).StackCount))
                        {
                            player.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                            trader.SendTradeStatus(TradeStatuses.TRADE_STATUS_CANCELLED);
                            return;
                        }
                    }
                }

                //Move items
                for (byte i = 0; i < TradeData.TRADE_SLOT_COUNT; i++)
                {
                    player.AddItem(othertrade.GetItem(i));
                    trader.AddItem(thistrade.GetItem(i));
                    trader.RemoveItem(othertrade.GetItem(i));
                    player.RemoveItem(thistrade.GetItem(i));
                }

                //Add money
                player.Money -= thistrade.Money;
                player.Money += othertrade.Money;
                trader.Money -= othertrade.Money;
                trader.Money += thistrade.Money;

                //Do spell


                trader.SendTradeStatus(TradeStatuses.TRADE_STATUS_COMPLETE);
                player.SendTradeStatus(TradeStatuses.TRADE_STATUS_COMPLETE);

                player.TradeInfo.Clear();
                trader.TradeInfo.Clear();
                trader.Dirty = true;
                player.Dirty = true;
            }
            else
            {
                trader.SendTradeStatus(TradeStatuses.TRADE_STATUS_ACCEPTED);
            }
        }
예제 #32
0
 public bool CommitTrades(IEnumerable <OMSTradeData> trades)
 {
     TradeData.AddRange(trades);
     SaveChanges();
     return(true);
 }