Example #1
0
        public void ShouldPrintDiscountWhenWednesday()
        {
            var dateTime = new DateTime(2020, 7, 15);

            List <LineItem> lineItems = new List <LineItem>()
            {
                new LineItem("milk", 10.0, 2),
                new LineItem("biscuits", 5.0, 5),
                new LineItem("chocolate", 20.0, 1),
            };
            var dateTimeInstance = new Mock <IDateTimeProvider>();

            dateTimeInstance.Setup(_ => _.Now()).Returns(dateTime);

            String       output  = "";
            OrderReceipt receipt = new OrderReceipt(new Order(null, null, lineItems, dateTimeInstance.Object));

            output = receipt.PrintReceipt();
            Assert.Contains("milk, 10 X 2, 20\n", output);
            Assert.Contains("biscuits, 5 X 5, 25\n", output);
            Assert.Contains("chocolate, 20 X 1, 20\n", output);
            Assert.Contains("税额: 6.5", output);
            Assert.Contains("折扣: 1.43", output);
            Assert.Contains("总价: 70.07", output);
        }
Example #2
0
        public void ShouldPrintCustomerInformationOnOrder()
        {
            Order        order   = new Order(new List <LineItem>(), Convert.ToDateTime("2020-7-16"));
            OrderReceipt receipt = new OrderReceipt(order, new StringBuilder());

            String output = receipt.PrintReceipt();

            Assert.Contains("=====老王超市,值得信赖======\n\n", output);
            Assert.Contains("2020年7月16日,星期四\n\n", output);
        }
Example #3
0
        public void shouldPrintCustomerInformationOnOrder()
        {
            Order        order   = new Order("Mr X", "Chicago, 60601", new List <LineItem>());
            OrderReceipt receipt = new OrderReceipt(order);

            String output = receipt.PrintReceipt();

            Assert.Contains("Mr X", output);
            Assert.Contains("Chicago, 60601", output);
        }
Example #4
0
 //发送购买配饰数据
 private void SendPetAccessoryOrder()
 {
     if (this.actionDatas.Count > 0)
     {
         ActionData actionData = this.actionDatas[0];
         Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>Header: {0}, Body: {1}, SendTimes: {2}", actionData.Header, actionData.Body, actionData.SendTimes);
         Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>Url: {0}", this.UrlProvider.BuyPetAccessories(this.LocalChildInfoAgent.getChildSN(), CupBuild.getCupSn()));
         this.NativeOkHttpMethodWrapper.post(this.UrlProvider.BuyPetAccessories(this.LocalChildInfoAgent.getChildSN(), CupBuild.getCupSn()), actionData.Header, actionData.Body, (result) =>
         {
             Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>GotResponse: {0}", result);
             OrderReceipt orderReceipt = this.JsonUtils.String2Json <OrderReceipt>(result);
             this.OrderReceiptSignal.Dispatch(orderReceipt);
             if (actionData.OnSuccess != null)
             {
                 Loom.QueueOnMainThread(() => actionData.OnSuccess(Result.Success(result)));
             }
             Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>Success:\n{0}", result);
             //检查数据
             if (this.actionDatas.Count > 0)
             {
                 this.lastActionData = null;
                 this.actionDatas.RemoveAt(0);   //移除已经执行成功的数据
                 if (this.actionDatas.Count > 0) //执行下一条数据
                 {
                     this.SendPetAccessoryOrder();
                 }
             }
         }, (errorResult) =>
         {
             Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>Error: {0}", errorResult.ErrorInfo);
             if (actionData.OnFailed != null)
             {
                 Loom.QueueOnMainThread(() => actionData.OnFailed(Result.Error(errorResult.ErrorInfo)));
             }
             //检查数据
             if (this.actionDatas.Count > 0)
             {
                 this.lastActionData = null;
                 if (this.actionDatas[0].SendTimes > 0)
                 {//重复上传(最多3次)
                     this.actionDatas[0].SendTimes -= 1;
                     Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>Repeat, SendTimes: {0}, Body: {1}", actionData.SendTimes, actionData.Body);
                     this.SendPetAccessoryOrder();
                 }
                 else
                 {//3次重传失败放弃
                     this.actionDatas.RemoveAt(0);
                     Debug.LogFormat("<><PetAccessoryUtils.SendPetAccessoryOrder>Abandon, SendTimes: {0}, Body: {1}", actionData.SendTimes, actionData.Body);
                 }
             }
         });
     }
 }
        public async Task <OrderReceipt> PlaceOrder(string appID, string mechantID, string deviceInfo, string description, IEnumerable <GoodsDetails> details, string attachNote, string orderID, string currency, int totalAmount, string clientIP, DateTime?validFrom, DateTime?expireAt, string couponTag, string callbackUrl, WxPayApiType apiType, string productID, WxPayPaymentLimit paymentLimit, string userOpenID)
        {
            dynamic postData = new WxPayData(_configuration.APIKey);

            postData.appid            = appID;
            postData.mch_id           = mechantID;
            postData.device_info      = deviceInfo;
            postData.body             = description;
            postData.detail           = SerializeGoodsDetails(details);
            postData.attach           = attachNote;
            postData.out_trade_no     = orderID;
            postData.fee_type         = currency;
            postData.total_fee        = totalAmount;
            postData.spbill_create_ip = clientIP;
            postData.time_start       = ConvertToEast8TimeString(validFrom);
            postData.time_expire      = ConvertToEast8TimeString(expireAt);
            postData.goods_tag        = couponTag;
            postData.notify_url       = callbackUrl;
            postData.trade_type       = apiType.ToPostDataString();
            postData.product_id       = productID;
            postData.limit_pay        = paymentLimit.ToPostDataString();
            postData.openid           = userOpenID;

            postData.Sign();

            HttpContent postContent = new ByteArrayContent(postData.ToByteArray());
            var         response    = await _httpClient.PostAsync("unifiedorder", postContent);

            if (!response.IsSuccessStatusCode)
            {
                throw new WxPayResponseInvalidException();
            }

            var resContent = await response.Content.ReadAsStringAsync();

            var resData = WxPayData.FromXml(resContent, _configuration.APIKey);

            if (resData.IsReturnedValid)
            {
                if (resData.VerifySignature())
                {
                    return(OrderReceipt.FromWxPayData(resData));
                }
                else
                {
                    throw new WxPaySignatureInvalidException("PlaceOrder return error");
                }
            }
            else
            {
                throw new WxPayResponseInvalidException(resData.ReturnedError);
            }
        }
Example #6
0
        public void Serialize()
        {
            Guid       orderId      = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8");
            var        receipt      = new OrderReceipt(orderId, Addresses.Admin, Addresses.Blacksmith, 10);
            Dictionary serialized   = (Dictionary)receipt.Serialize();
            var        deserialized = new OrderReceipt(serialized);

            Assert.Equal(orderId, deserialized.OrderId);
            Assert.Equal(Addresses.Admin, deserialized.BuyerAgentAddress);
            Assert.Equal(Addresses.Blacksmith, deserialized.BuyerAvatarAddress);
            Assert.Equal(10, deserialized.TransferredBlockIndex);
        }
Example #7
0
        public void Serialize_DotNet_Api()
        {
            Guid orderId   = new Guid("6d460c1a-755d-48e4-ad67-65d5f519dbc8");
            var  receipt   = new OrderReceipt(orderId, Addresses.Admin, Addresses.Blacksmith, 10);
            var  formatter = new BinaryFormatter();

            using var ms = new MemoryStream();
            formatter.Serialize(ms, receipt);
            ms.Seek(0, SeekOrigin.Begin);

            var deserialized = (OrderReceipt)formatter.Deserialize(ms);

            Assert.Equal(receipt.Serialize(), deserialized.Serialize());
        }
Example #8
0
        public void shouldPrintCustomerInformationOnOrder()
        {
            var dateTimeInstance = new Mock <IDateTimeProvider>();
            var dateTime         = new DateTime(2020, 7, 15);

            dateTimeInstance.Setup(_ => _.Now()).Returns(dateTime);
            Order        order   = new Order("Mr X", "Chicago, 60601", new List <LineItem>(), dateTimeInstance.Object);
            OrderReceipt receipt = new OrderReceipt(order);

            String output = receipt.PrintReceipt();

            Assert.Contains(dateTime.ToString("yyyy年M月d日, dddd", new CultureInfo("zh-cn")), output);
            Assert.Contains("Mr X", output);
            Assert.Contains("Chicago, 60601", output);
        }
Example #9
0
        public void ShouldDiscountAndPrintDiscountInfoWhenWednesday()
        {
            List <LineItem> lineItems = new List <LineItem>()
            {
                new LineItem("milk", 10.0, 2),
                new LineItem("biscuits", 5.0, 5),
                new LineItem("chocolate", 20.0, 1),
            };
            OrderReceipt receipt = new OrderReceipt(new Order(lineItems, Convert.ToDateTime("2020-7-15")), new StringBuilder());

            String output = receipt.PrintReceipt();

            Assert.Contains("折扣:\t1.43", output);
            Assert.Contains("总价:\t70.07", output);
        }
Example #10
0
        public ResResultModel GetOrderIdByReceipt(string orderNum)
        {
            if (string.IsNullOrWhiteSpace(orderNum))
            {
                return(ResResult.Response(false, "参数值不正确", ""));
            }

            try
            {
                var bll = new OrderReceipt();
                return(ResResult.Response(true, "调用成功", bll.GetOrderId(orderNum)));
            }
            catch (Exception ex)
            {
                return(ResResult.Response(false, ex.Message, ""));
            }
        }
Example #11
0
        public void ShouldPrintLineItemAndSalesTaxInformation()
        {
            List <LineItem> lineItems = new List <LineItem>()
            {
                new LineItem("milk", 10.0, 2),
                new LineItem("biscuits", 5.0, 5),
                new LineItem("chocolate", 20.0, 1),
            };
            OrderReceipt receipt = new OrderReceipt(new Order(null, null, lineItems));

            String output = receipt.PrintReceipt();

            Assert.Contains("milk\t10\t2\t20\n", output);
            Assert.Contains("biscuits\t5\t5\t25\n", output);
            Assert.Contains("chocolate\t20\t1\t20\n", output);
            Assert.Contains("Sales Tax\t6.5", output);
            Assert.Contains("Total Amount\t71.5", output);
        }
Example #12
0
        public void ShouldPrintLineItemAndSalesTaxInformation()
        {
            List <LineItem> lineItems = new List <LineItem>()
            {
                new LineItem("milk", 10.0, 2),
                new LineItem("biscuits", 5.0, 5),
                new LineItem("chocolate", 20.0, 1),
            };
            OrderReceipt receipt = new OrderReceipt(new Order(lineItems, Convert.ToDateTime("2020-7-16")), new StringBuilder());

            String output = receipt.PrintReceipt();

            Assert.Contains("milk,10*2,20\n", output);
            Assert.Contains("biscuits,5*5,25\n", output);
            Assert.Contains("chocolate,20*1,20\n", output);
            Assert.Contains("-----------------------\n", output);
            Assert.Contains("税额:\t6.5\n", output);
            Assert.Contains("总价:\t71.5", output);
        }
Example #13
0
        public PrintOrderInfo GetPrintOrderReceipt(Guid Id)
        {
            var data = new PrintOrderInfo();

            data.Title      = "收货单";
            data.SPrintDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");

            var bll   = new OrderReceipt();
            var oInfo = bll.GetModel(Id);

            data.OrderCode         = oInfo.OrderCode;
            data.PurchaseOrderCode = "";
            data.SupplierName      = "";
            data.SPlanArrivalTime  = "";
            data.SPlanArrivalTime  = "";

            var t1 = Task.Factory.StartNew(() =>
            {
                BarcodeHelper bh     = new BarcodeHelper();
                data.BarcodeImageUri = bh.CreateBarcode(data.OrderCode);
            });

            var orpBll   = new OrderReceiptProduct();
            var sqlWhere = "and orp.OrderId = @OrderId ";
            var parm     = new SqlParameter("@OrderId", oInfo.Id);
            var pList    = orpBll.GetListByJoin(sqlWhere, parm);

            if (pList != null && pList.Count > 0)
            {
                var cargoList = new List <PrintOrderCargoInfo>();
                foreach (var item in pList)
                {
                    cargoList.Add(new PrintOrderCargoInfo("", item.ProductCode, item.ProductName, "", "", item.PackageCode, item.PackageName, item.Unit, item.ExpectedQty, item.ReceiptQty, ""));
                }
                data.CargoList = cargoList;
                //data.CargoList = JsonConvert.SerializeObject(cargoList);
            }

            t1.Wait();

            return(data);
        }
Example #14
0
        public JsonResult Create(Order newOrder)
        {
            Customer cust = GetCustomer(newOrder.CustomerId);

            var order = new Order
            {
                CustomerId = newOrder.CustomerId,
                Items      = SyncProducts(newOrder)
            };

            DBHelper.CreateOrder(order);
            UpdateCustomerOrders(cust, order);

            OrderReceipt receipt = new OrderReceipt(order);

            return(new JsonResult()
            {
                Data = receipt, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Example #15
0
        /************************************************Unity方法与事件***********************************************/

        /************************************************自 定 义 方 法************************************************/
        //打开页面
        public override void Open(object param = null)
        {
            base.Open();
            this.beginTime = DateTime.Now;

            if (this.audioPlayer == null)
            {
                this.audioPlayer = this.gameObject.AddComponent <AudioSource>();
            }

            SoundPlayer.GetInstance().StopAllSoundExceptMusic();
            SoundPlayer.GetInstance().PlaySoundInChannal("mall_purchase_qr", this.audioPlayer, 0.2f);

            if (param != null && this.QRCode != null)
            {
                this.orderReceipt = param as OrderReceipt;
                if (this.orderReceipt == null)
                {
                    return;
                }
                Debug.LogFormat("<><QRCodeView.Open>orderSN: {0}", this.orderReceipt.order_sn);
                Texture2D texture = this.QRCodeUtils.GenerateQRImageFreeSize(this.orderReceipt.code_url, 256, 256);
                if (texture != null)
                {
                    Debug.LogFormat("<><QRCodeView.Open>Texture, width: {0}, height: {1}", texture.width, texture.height);
                }
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
                if (sprite != null)
                {
                    Debug.LogFormat("<><QRCodeView.Open>Sprite, rect: {0}", sprite.rect);
                }
                this.QRCode.sprite = sprite;
                this.InvokeRepeating("GetPaymentResult", 0, 2f);
            }
            RoleManager.Instance.Hide();
        }
Example #16
0
        public void ShouldPrintLineItemAndSalesTaxInformation()
        {
            List <LineItem> lineItems = new List <LineItem>()
            {
                new LineItem("milk", 10.0, 2),
                new LineItem("biscuits", 5.0, 5),
                new LineItem("chocolate", 20.0, 1),
            };

            var dateTime         = new DateTime(2020, 7, 13);
            var dateTimeInstance = new Mock <IDateTimeProvider>();

            dateTimeInstance.Setup(_ => _.Now()).Returns(dateTime);

            OrderReceipt receipt = new OrderReceipt(new Order(null, null, lineItems, dateTimeInstance.Object));
            String       output  = receipt.PrintReceipt();

            Assert.Contains("milk, 10 X 2, 20\n", output);
            Assert.Contains("biscuits, 5 X 5, 25\n", output);
            Assert.Contains("chocolate, 20 X 1, 20\n", output);
            Assert.Contains("税额: 6.5", output);
            Assert.DoesNotContain("折扣:", output);
            Assert.Contains("总价: 71.5", output);
        }
Example #17
0
        public static OrderReceipt GetPendingOrderReceipt(PizzaOrder pendingOrder)
        {
            OrderReceipt pendingReceipt = new OrderReceipt();

            List <PizzaSizeDTO> sizes = ApiAccess.getItemsFromApi <List <PizzaSizeDTO> >("sizes");
            var     matchingSizes     = sizes.Where(x => x.Name == pendingOrder.size);
            decimal sizePrice         = matchingSizes.First().Price;

            List <CrustTypeDTO> crusts = ApiAccess.getItemsFromApi <List <CrustTypeDTO> >("crusts");
            var     matchingCrusts     = crusts.Where(x => x.Name == pendingOrder.crust);
            decimal crustPrice         = matchingCrusts.First().Price;

            List <SauceTypeDTO> sauces = ApiAccess.getItemsFromApi <List <SauceTypeDTO> > ("sauces");
            var     matchingSauces     = sauces.Where(x => x.Name == pendingOrder.sauce);
            decimal saucePrice         = matchingSauces.First().Price;

            List <CheeseTypeDTO> cheeses = ApiAccess.getItemsFromApi <List <CheeseTypeDTO> >("cheeses");
            var     matchingCheeses      = cheeses.Where(x => x.Name == pendingOrder.cheese);
            decimal cheesePrice          = matchingCheeses.First().Price;

            decimal           toppingTotalPrice = 0;
            string            toppingString     = "";
            List <ToppingDTO> vegetableToppings = ApiAccess.getItemsFromApi <List <ToppingDTO> >("vegetabletoppings");

            var matchingVegetableToppings = vegetableToppings.Where(x => x.Name == pendingOrder.vegetableToppings);

            toppingTotalPrice = toppingTotalPrice + matchingVegetableToppings.First().Price;
            toppingString     = toppingString + " " + pendingOrder.vegetableToppings;

            List <ToppingDTO> meatToppings = ApiAccess.getItemsFromApi <List <ToppingDTO> >("meattoppings");

            var matchingMeatToppings = meatToppings.Where(x => x.Name == pendingOrder.meatToppings);

            toppingTotalPrice = toppingTotalPrice + matchingMeatToppings.First().Price;
            toppingString     = toppingString + " " + pendingOrder.meatToppings;

            List <ToppingDTO> additionalCheeseToppings = ApiAccess.getItemsFromApi <List <ToppingDTO> >("additionalcheesetoppings");


            var matchingAdditionalCheeseToppings = additionalCheeseToppings.Where(x => x.Name == pendingOrder.additionalCheeseToppings);

            toppingTotalPrice = toppingTotalPrice + matchingAdditionalCheeseToppings.First().Price;
            toppingString     = toppingString + " " + pendingOrder.additionalCheeseToppings;

            pendingReceipt.cheese          = pendingOrder.cheese;
            pendingReceipt.size            = pendingOrder.size;
            pendingReceipt.sauce           = pendingOrder.sauce;
            pendingReceipt.crust           = pendingOrder.crust;
            pendingReceipt.deliveryAddress = (pendingOrder.addressStreet + " " + pendingOrder.addressCity + " " + pendingOrder.addressState + " " + pendingOrder.addressZip);
            pendingReceipt.paymentType     = pendingOrder.paymentMethod;

            decimal subTotalAmt = (sizePrice + cheesePrice + saucePrice + crustPrice + toppingTotalPrice);

            pendingReceipt.subtotal = subTotalAmt.ToString();

            pendingReceipt.taxes = (1).ToString();

            decimal totalAmt = (sizePrice + cheesePrice + saucePrice + crustPrice + toppingTotalPrice) + 1;

            pendingReceipt.total = totalAmt.ToString();

            pendingReceipt.toppings = toppingString;
            return(pendingReceipt);
        }
        //点击确认
        public void Confirm()
        {
            if (this.accessoryTypes.BackButtonSelected)
            {//退出换装页
                this.CloseViewSignal.Dispatch(true);
            }
            else if (!this.accessories.HasItems)
            {//如果当前商店中无配饰
                return;
            }
            else if (!this.accessories.CurrentButton.Accessory.Suitable(this.PlayerDataManager.CurrentPet) && !this.suitLockView.IsOpen)
            {//显示配饰不适用提示页面
                this.audioPlayer.Stop();
                this.suitLockView.Open(this.accessories.CurrentButton.Accessory);
                FlurryUtil.LogEventWithParam("mall_scene_lock_suitable", "accessory_name", this.accessories.CurrentButton.Accessory.Name);
            }
            else if (this.suitLockView.IsOpen)
            {//关闭配饰不适用提示页面
                this.suitLockView.Close();
            }
            else if (this.accessories.CurrentButton.Paid && !this.accessories.CurrentButton.Worn)
            {//已拥有:穿上当前配饰
                this.PutOn(this.accessories.CurrentButton.Accessory);
                this.PlaySound("mall_put_on_accessory");
                FlurryUtil.LogEventWithParam("mall_scene_change", "accessory_name", this.accessories.CurrentButton.Accessory.Name);
            }
            else if (this.accessories.CurrentButton.Paid && this.accessories.CurrentButton.Worn)
            {//已拥有:脱掉当前配饰
                this.TakeOff(this.accessories.CurrentButton.Accessory);
                this.PlaySound(this.accessories.CurrentButton.Accessory.CanWear ? "mall_take_off_accessory" : "mall_spirit_out");
            }
            else if (this.accessories.CurrentButton.Accessory.Level > this.PlayerDataManager.playerLevel && !this.levelLockView.IsOpen)
            {//显示等级不够提示页面
                this.audioPlayer.Stop();
                this.levelLockView.Open(this.accessories.CurrentButton.Accessory);
                FlurryUtil.LogEventWithParam("mall_scene_lock_level", "accessory_name", this.accessories.CurrentButton.Accessory.Name);
            }
            else if (this.levelLockView.IsOpen)
            {//关闭等级不够提示页面
                this.levelLockView.Close();
            }
            else if (!this.accessories.CurrentButton.Accessory.Opened && !this.openLockView.IsOpen)
            {//显示未开放提示页面
                this.audioPlayer.Stop();
                this.openLockView.Open(this.accessories.CurrentButton.Accessory);
            }
            else if (this.openLockView.IsOpen)
            {//关闭未开放提示页面
                this.openLockView.Close();
            }
            else if (this.goalLockView.IsOpen)
            {//关闭饮水目标未达标提示页面
                this.goalLockView.Close();
            }
            else if (this.coinLockView.IsOpen)
            {//关闭金币不足提示页面
                this.coinLockView.Close();
            }
            else if (this.wifiLockView.IsOpen)
            {//关闭无网络连接提示页面
                this.wifiLockView.Close();
            }
            else if (this.qrCodeView.IsOpen)
            {//关闭二维码页面
                this.qrCodeView.Close();
            }
            else if (!this.accessories.CurrentButton.Paid && this.accessories.CurrentButton.Accessory.Coin)
            {//金币购买的配饰:钱够→扣钱→配饰进包裹→记录穿戴数据→配饰图标状态更新
                if (this.FundDataManager.GetItemCount(this.FundDataManager.GetCoinId()) >= this.accessories.CurrentButton.Accessory.Price)
                {
                    this.accessories.CurrentButton.Paid = true;
                    this.AccessoryDataManager.AddItem(this.accessories.CurrentButton.Accessory.ID);                                         //配饰添加到包裹
                    this.FundDataManager.ExpendCoin(this.FundDataManager.GetCoinId(), (int)this.accessories.CurrentButton.Accessory.Price); //扣钱
                    SoundPlayer.GetInstance().StopAllSoundExceptMusic();
                    SoundPlayer.GetInstance().PlaySoundInChannal("mall_purchase_qr_complete", this.audioPlayer, 0.2f);
                    this.PutOn(this.accessories.CurrentButton.Accessory);
                    ExpUI.Instance.Show(this.accessories.CurrentButton.Accessory.Exp, 0, -25, 25, GameObject.FindGameObjectWithTag("ExpUILayer").transform);
                    this.PlayerDataManager.exp += this.accessories.CurrentButton.Accessory.Exp;
                    this.UIState.PushNewState(UIStateEnum.eExpIncrease, this.PlayerDataManager.GetExpPercent());
                    this.UpdateExpAndCoinSignal.Dispatch();
                    FlurryUtil.LogEventWithParam("mall_scene_purchase", "accessory_name", this.accessories.CurrentButton.Accessory.Name);
                }
                else if (!this.coinLockView.IsOpen)
                {//显示金币不足提示页面
                    this.audioPlayer.Stop();
                    this.coinLockView.Open();
                }
            }
            else if (!this.accessories.CurrentButton.Paid && this.accessories.CurrentButton.Accessory.Cash && !this.qrCodeView.IsOpen)
            {     //货币购买的配饰:向服务器发送请求,获取二维码并打开页面显示
                if (this.PlayerDataManager.currIntake < this.PlayerDataManager.GetDailyGoal() && !this.goalLockView.IsOpen)
                { //显示饮水目标未达标提示页面
                    this.audioPlayer.Stop();
                    this.goalLockView.Open(this.accessories.CurrentButton.Accessory);
                    FlurryUtil.LogEventWithParam("mall_scene_lock_goal", "accessory_name", this.accessories.CurrentButton.Accessory.Name);
                }
#if !UNITY_EDITOR && UNITY_ANDROID
                else if (!NativeWifiManager.Instance.IsConnected() && !this.wifiLockView.IsOpen)
                {//显示无网络连接提示页面
                    this.audioPlayer.Stop();
                    this.wifiLockView.Open();
                }
#else
                else if (!this.wifiLockView.IsOpen)
                {//显示无网络连接提示页面
                    this.audioPlayer.Stop();
                    this.wifiLockView.Open();
                }
#endif
                else
                {
#if !UNITY_EDITOR && UNITY_ANDROID
                    this.IsBuying = true;
                    PetAccessoryOrder order = new PetAccessoryOrder()
                    {
                        items = new List <PetAccessory>()
                        {
                            new PetAccessory()
                            {
                                sn = this.accessories.CurrentButton.Accessory.ID.ToString(), count = 1
                            }
                        },
                        remark = string.Format("CupSn:{0}, ChildSn:{1}", CupBuild.getCupSn(), this.LocalChildInfoAgent.getChildSN())
                    };

                    this.PetAccessoryUtils.BuyPetAccessories(order, (result) =>
                    {
                        this.IsBuying             = false;
                        OrderReceipt orderReceipt = this.JsonUtils.String2Json <OrderReceipt>(result.info);
                        if (orderReceipt != null && !string.IsNullOrEmpty(orderReceipt.status) && orderReceipt.status.ToUpper() == "OK")
                        {
                            this.audioPlayer.Stop();
                            this.qrCodeView.Open(orderReceipt);
                            FlurryUtil.LogEventWithParam("mall_scene_qr", "accessory_name", this.accessories.CurrentButton.Accessory.Name);
                        }
                        else
                        {
                            Debug.LogError("<><PetPageView.Confirm>orderReceipt is null");
                        }
                    },
                                                             (error) =>
                    {
                        this.IsBuying = false;
                        Debug.LogErrorFormat("<><PetPageView.Confirm>BuyPetAccessories, error: {0}", error.info);
                    });
#else
                    this.audioPlayer.Stop();
                    this.qrCodeView.Open(null);
#endif
                }
            }
        }
Example #19
0
        // json is true when checkout is done from an iframe, eg. facebook page
        public ActionResult create(CheckoutStatus status, string shippingmethod, string paymentmethod, bool isJson = false)
        {
            Debug.Assert(!cart.orderid.HasValue);

            var shop_owner = cart.MASTERsubdomain.organisation.users.First();
            var currency   = cart.MASTERsubdomain.currency.ToCurrency();
            var buyer      = cart.user;

            var transaction = new Transaction(cart.MASTERsubdomain, buyer, TransactionType.INVOICE, repository, sessionid.Value);

            transaction.CreateTransaction(
                repository.GetNewOrderNumber(subdomainid.Value, TransactionType.INVOICE),
                DateTime.UtcNow,
                cart.MASTERsubdomain.paymentTerms,
                currency.id);

            // mark as sent
            transaction.UpdateOrderStatus(OrderStatus.SENT);

            var shoppingcart = new ShoppingCart(currency.code)
            {
                shippingMethod = shippingmethod
            };

            foreach (var item in cart.cartitems)
            {
                var checkOutItem = item.product_variant.ToCheckoutItem(item.quantity, sessionid);
                var orderItem    = new orderItem
                {
                    description = item.product_variant.ToProductFullTitle(),
                    variantid   = item.product_variant.id,
                    unitPrice   = item.product_variant.product.ToUserPrice(cart.userid.Value),
                    tax         = item.product_variant.product.tax,
                    quantity    = item.quantity
                };
                transaction.AddOrderItem(orderItem, item.product_variant.product.products_digitals);
                // update inventory
                transaction.UpdateInventoryItem(orderItem, item.quantity);

                shoppingcart.items.Add(checkOutItem);
            }

            if (!cart.isDigitalOrder())
            {
                shoppingcart.CalculateShippingCost(cart.cartitems.Select(x => x.product_variant).AsQueryable(), cart.MASTERsubdomain, buyer);

                if (cart.cartitems.Select(x => x.product_variant.product.shippingProfile).UseShipwire())
                {
                    transaction.UpdateShippingMethod(shoppingcart.shipwireShippingName, shoppingcart.shippingMethod);
                }
                else
                {
                    transaction.UpdateShippingMethod(shoppingcart.shippingMethod);
                }
            }

            transaction.UpdateTotal(cart.coupon);
            transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE

            repository.AddActivity(buyer.id,
                                   new ActivityMessage(transaction.GetID(), shop_owner.id,
                                                       ActivityMessageType.INVOICE_NEW,
                                                       new HtmlLink(transaction.GetOrderNumber(), transaction.GetID()).ToTransactionString(TransactionType.INVOICE)), subdomainid.Value);

            // add checkout note as a comment
            if (!string.IsNullOrEmpty(cart.note))
            {
                transaction.AddComment(cart.note, cart.userid.Value);
            }

            // add comment if shipping method not specified
            if (!transaction.HasShippingMethod() && !cart.isDigitalOrder())
            {
                transaction.AddComment(OrderComment.SHIPPING_WAIT_FOR_COST);
            }

            // set cart as processed
            cart.orderid = transaction.GetID();

            // save payment method
            if (!string.IsNullOrEmpty(paymentmethod))
            {
                switch (paymentmethod)
                {
                case "paypal":
                    cart.paymentMethod = PaymentMethodType.Paypal.ToString();
                    break;

                default:
                    cart.paymentMethod   = PaymentMethodType.Custom.ToString();
                    cart.paymentCustomId = long.Parse(paymentmethod);
                    break;
                }
            }

            repository.Save();

            // send emails
            // send mail to buyer
            var buyerEmailContent = new OrderReceipt()
            {
                viewloc =
                    cart.MASTERsubdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()),
                shopname        = cart.MASTERsubdomain.storeName,
                date            = transaction.GetOrderDate().ToShortDateString(),
                shippingAddress = transaction.GetShippingAddress().ToHtmlString(),
                billingAddress  = transaction.GetBillingAddress().ToHtmlString(),
                subtotal        = string.Format("{0}{1}", currency.symbol, transaction.GetSubTotal().ToString("n" + currency.decimalCount)),
                shippingcost    = string.Format("{0}{1}", currency.symbol, transaction.GetShippingCost().ToString("n" + currency.decimalCount)),
                discount        = string.Format("{0}{1}", currency.symbol, transaction.GetDiscount().ToString("n" + currency.decimalCount)),
                totalcost       = string.Format("{0}{1}{2}", currency.code, currency.symbol, transaction.GetTotal().ToString("n" + currency.decimalCount)),
                orderitems      = transaction
                                  .GetOrderItems()
                                  .Select(x => string.Format("{0} x {1}{2} {3}",
                                                             x.quantity,
                                                             currency.symbol,
                                                             x.unitPrice.Value.ToString("n" + currency.decimalCount),
                                                             x.description))
            };

            // send mail to seller
            var sellerEmailContent = new NewOrderEmailContent
            {
                viewloc =
                    cart.MASTERsubdomain.ToHostName().ToDomainUrl(transaction.GetOrderLink()),
                sender = buyer.organisation1.name
            };

            string buyer_subject;
            string seller_subject;

            switch (status)
            {
            case CheckoutStatus.SHIPPING_FAIL:
                buyer_subject = string.Format("[{0}]Invoice #{1}", cart.MASTERsubdomain.name,
                                              transaction.GetOrderNumber());
                seller_subject = string.Format("[{0}]New Invoice #{1} : ACTION REQUIRED", cart.MASTERsubdomain.name,
                                               transaction.GetOrderNumber());
                buyerEmailContent.message =
                    "Thank you for placing an order with us. Unfortunately, we are not able to provide a shipping cost at this moment. We will contact you once we have the shipping costs. You can check the status of your order by following the link below:";
                sellerEmailContent.message = "A customer has placed an order on your online store. However, the shipping cost could not be calculated. You will need to manually update the invoice with the shipping cost. To update the invoice, follow the link below:";
                break;

            case CheckoutStatus.SHIPPING_NONE:
            case CheckoutStatus.SHIPPING_OK:
                buyer_subject = string.Format("[{0}]Invoice #{1} confirmed", cart.MASTERsubdomain.name,
                                              transaction.GetOrderNumber());
                seller_subject = string.Format("[{0}]New Invoice #{1}", cart.MASTERsubdomain.name,
                                               transaction.GetOrderNumber());

                if (cart.isDigitalOrder())
                {
                    buyerEmailContent.message = "Download links will be provided once payment is confirmed";
                }
                sellerEmailContent.message = "A customer has placed an order on your online store. To view the invoice, follow the link below:";
                break;

            default:
                throw new ArgumentOutOfRangeException("status");
            }

            this.SendEmail(EmailViewType.INVOICEORDER_NEW, sellerEmailContent, seller_subject,
                           shop_owner.GetEmailAddress(), shop_owner.ToFullName(), buyer);

            this.SendEmail(EmailViewType.ORDER_RECEIPT, buyerEmailContent, buyer_subject,
                           buyer.GetEmailAddress(), buyer.ToFullName(), shop_owner);

            // handle payment
            string redirecturl = "";

            if (!string.IsNullOrEmpty(paymentmethod))
            {
                switch (paymentmethod)
                {
                case "paypal":
                    string returnUrl;
                    if (isJson)
                    {
                        returnUrl = string.Format("{0}/checkout/order/{1}/close", GeneralConstants.HTTP_SECURE, cart.id);
                    }
                    else
                    {
                        returnUrl = string.Format("{0}/checkout/order/{1}", GeneralConstants.HTTP_SECURE, cart.id);
                    }
                    var pworker = new PaypalWorker(cart.id.ToString(),
                                                   transaction,
                                                   repository,
                                                   cart.MASTERsubdomain.GetPaypalID(),
                                                   transaction.GetCurrency().id,
                                                   returnUrl);
                    try
                    {
                        redirecturl = pworker.GetPaymentUrl();
                    }
                    catch (Exception ex)
                    {
                        Syslog.Write(ex);
                        return(RedirectToAction("Index", "Error"));
                    }
                    break;

                default:
                    break;
                }
            }

            if (!string.IsNullOrEmpty(redirecturl))
            {
                return(Redirect(redirecturl));
            }

            if (isJson)
            {
                return(View("close"));
            }

            return(RedirectToAction("Index"));
        }