예제 #1
0
    // Start is called before the first frame update
    void Start()
    {
        nextButton = this.gameObject.GetComponent <Button>();
        nextButton.onClick.AddListener(onNextClick);

        receiptManager = GameObject.FindGameObjectWithTag("ReceiptManager").GetComponent <ReceiptManager>();
    }
        public ActionResult AddOrderToDB(FormCollection collection)
        {
            var name   = collection["Name"];
            var email  = collection["Email"];
            var model  = GetCartDetails(out double total);
            var order  = CreateOrder(model);
            var client = new Client
            {
                Name  = name,
                Email = email,
            };

            db.Client.Add(client);
            order.Client = client;
            db.Order.Add(order);
            db.SaveChanges();
            string directoryPath    = "~/ReportTemplates/";
            string fileName         = $"Receipt_Order{order.ID}.docx";
            string templateFile     = "ReceiptTemplate.docx";
            string receiptFileName  = Server.MapPath(directoryPath + fileName);
            string templateFileName = Server.MapPath(directoryPath + templateFile);

            ReceiptManager.CreateReceipt(order, templateFileName, receiptFileName);
            Response.ContentType = "Application/msword";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.TransmitFile(receiptFileName);
            Response.End();
            string virtualPath = Request.MapPath(directoryPath + fileName);

            System.IO.File.Delete(virtualPath);
            Session["Cart"] = null;

            return(RedirectToAction("Index", "Home"));
        }
예제 #3
0
 public ClientResponse FindProductAndService(String q, Int32 limit)
 {
     return(new ClientResponse(() =>
     {
         using (var receiptManager = new ReceiptManager(null))
             return receiptManager.SearchProductAndService((Int32)Company.MatrixId, q, limit).ToArray();
     }));
 }
        // GET: Receipt
        public ActionResult ViewByCustomer(int id)
        {
            var Model = ReceiptManager.GetAllForCustomer(id);

            ViewBag.cityId     = CustomerManager.Get(id).CityID;
            ViewBag.customerId = id;
            return(View(Model));
        }
예제 #5
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //建立資料model及ReceiptManager的物件
            var manager = new ReceiptManager();
            var model   = new ReceiptModel();

            //建立5個變數來存取各個輸入值
            string inputRecNo  = this.txtReceiptNumber.Text.Trim();
            string inputDate   = this.lbDate.Text.Trim();
            string dplCompany  = this.dplCompany.SelectedValue;
            string inputAmount = this.txtAmount.Text.Trim();
            string dplRE       = this.dplRE.SelectedValue;

            //檢查輸入值(發票號碼、日期、金額)
            if (string.IsNullOrEmpty(inputRecNo) || string.IsNullOrEmpty(inputAmount) || string.Equals(inputDate, "請選擇日期"))
            {
                //日期沒輸入會變成紅色
                if (string.Equals(inputDate, "請選擇日期"))
                {
                    this.lbDate.ForeColor = System.Drawing.Color.Red;
                }

                this.lblMsg.Text = "請填入完整的發票資料";
                return;
            }
            else if (ReceiptDetailHelper.checkReceiptNumber(inputRecNo) != string.Empty)
            {
                this.lblMsg.Text = "請填入正確的發票格式";
                return;
            }
            else if (ReceiptDetailHelper.checkAmount(inputAmount) != string.Empty)
            {
                this.lblMsg.Text = "金額只能填入數字";
                return;
            }

            //上面檢查都通過後,將輸入值存入資料model
            model.ReceiptNumber   = inputRecNo;
            model.Date            = DateTime.Parse(inputDate);
            model.Company         = dplCompany;
            model.Amount          = decimal.Parse(inputAmount);
            model.Revenue_Expense = (Revenue_Expense)Enum.Parse(typeof(Revenue_Expense), dplRE);

            //分成更新模式及新增模式
            //更新模式下將資料model更新至資料庫
            //新增模式下將資料model存入資料庫
            if (ReceiptDetailHelper.isUpdateMode())
            {
                manager.UpdateReceipt(model);
                this.lblMsg.Text = "發票更新成功";
            }
            else
            {
                manager.CreateReceipt(model);
                this.lblMsg.Text = "發票新增成功";
            }
        }
예제 #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //找出MasterPage中的Label控制項並給與當前表單名稱
            MainMaster masterPage = this.Master as MainMaster;
            Label      label      = masterPage.FindControl("lbPageName") as Label;

            label.Text = "發票清單";

            var manager = new ReceiptManager();
            var list    = manager.GetInvoices();

            this.repInvoice.DataSource = list;
            this.repInvoice.DataBind();
        }
        public ActionResult Index(ReceiptTestViewModel model)
        {
            ReceiptManager receiptManager = new ReceiptManager();
            var env = AppleReceiptVerifier.Environments.Production;
            if (model.Environment == "sandbox")
            {
                env = AppleReceiptVerifier.Environments.Sandbox;
            }

            var response = receiptManager.ValidateReceipt(env, model.ReceiptData, model.Password);
            model.ReceiptResponse = response;

            return this.View(model);
        }
예제 #8
0
        public ActionResult Index(ReceiptTestViewModel model)
        {
            ReceiptManager receiptManager = new ReceiptManager();
            var            env            = AppleReceiptVerifier.Environments.Production;

            if (model.Environment == "sandbox")
            {
                env = AppleReceiptVerifier.Environments.Sandbox;
            }

            var response = receiptManager.ValidateReceipt(env, model.ReceiptData, model.Password);

            model.ReceiptResponse = response;

            return(this.View(model));
        }
예제 #9
0
        protected void repInvoice_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string cmdName = e.CommandName;
            string arg     = e.CommandArgument.ToString();
            var    manager = new ReceiptManager();

            if (cmdName == "DeleteItem")
            {
                manager.DeleteReceipt(arg);
                this.LoadRepeater();
            }

            if (cmdName == "UpdateItem")
            {
                string targetUrl = "~/ReceiptDetail.aspx?RepNo=" + arg;
                Response.Redirect(targetUrl);
            }
        }
예제 #10
0
        //用發票號碼去DB讀取對應的發票資料
        private void LoadReceipt(string ReceiptNumber)
        {
            //讀取資料並放入資料model
            var manager = new ReceiptManager();
            var model   = manager.GetReceipt(ReceiptNumber);

            //如果讀取不到資料,回到發票總覽頁面
            if (model == null)
            {
                Response.Redirect("~/ReceiptList.aspx");
            }

            //讀取到的資料放入畫面中各個使用者輸入項目裡
            this.txtReceiptNumber.Text    = model.ReceiptNumber;
            this.lbDate.Text              = string.Format("{0:yyyy-MM-dd}", model.Date);
            this.dplCompany.SelectedValue = model.Company;
            this.txtAmount.Text           = model.Amount.ToString();
            this.dplRE.SelectedValue      = ((int)model.Revenue_Expense).ToString();
        }
예제 #11
0
    /// <summary>
    /// this method fill the cboSaleAndOs
    /// </summary>
    private void LoadCboSaleAndOs(Int32 customerId)
    {
        ListItem  lstItem;
        DataTable dtSaleAndOs = ReceiptManager.GetSaleAndOSNonInvoiced(Company.CompanyId, customerId);

        cboSaleAndOs.Items.Clear();
        cboSaleAndOs.Items.Add(String.Empty);
        foreach (DataRow row in dtSaleAndOs.Rows)
        {
            lstItem      = new ListItem();
            lstItem.Text = row["number"].ToString();
            if (row["number"].ToString().Contains("VE-"))
            {
                lstItem.Text += Convert.ToDateTime(row["date"]).ToShortDateString();
            }
            lstItem.Value = row["id"].ToString();
            cboSaleAndOs.Items.Add(lstItem);
        }
    }
예제 #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //如果第一次載入這個Page
            if (!IsPostBack)
            {
                //讀取DB的Company表來設定下拉選單內容
                DDLManager ddlManager   = new DDLManager();
                DataTable  ddlDataTable = ddlManager.GetCompanyDDL();
                this.dplCompany.DataSource     = ddlDataTable;
                this.dplCompany.DataValueField = "Cid";
                this.dplCompany.DataTextField  = "Name";
                this.dplCompany.DataBind();

                //宣告變數存取QueryString
                string RepNumber = Request.QueryString["RepNo"];

                //分為更新模式及新增模式
                if (ReceiptDetailHelper.isUpdateMode())
                {
                    this.h1Title.InnerText = "修改發票";

                    //讀取DB內的資料顯示在畫面
                    this.LoadReceipt(RepNumber);

                    //鎖定發票號碼
                    this.txtReceiptNumber.Enabled   = false;
                    this.txtReceiptNumber.BackColor = System.Drawing.Color.LightGray;
                }
                else if (!string.IsNullOrEmpty(RepNumber))
                {
                    //Uri的QueryString被更改時、直接跳回發票總覽頁面
                    var manager = new ReceiptManager();
                    if (manager.GetReceipt(RepNumber) == null)
                    {
                        Response.Redirect("~/ReceiptList.aspx");
                    }
                }
                else
                {
                    this.h1Title.InnerText = "新增發票";
                }
            }
        }
        public void GeneratePaymentsToAllLines_CreatePaymentsforAllCustomerLines_ReturnListOfPayments()
        {
            //arrange
            var lines    = _data.GetAllLinesWithPackageAndFriend();
            var customer = _data.GetCustomer();

            customer.CustomerType = _data.GetCustomerType(CustomerTypeEnum.Private);
            _mock.Setup(s => s.Line.GetAllLinesWithAllEntities())
            .Returns(lines);

            _mock.Setup(s => s.Customer.GetCustomerWithTypeAndLines(It.IsAny <int>()))
            .Returns(customer);

            _manager = new ReceiptManager(_mock.Object);

            //act
            var res = _manager.GeneratePaymentsToAllLines(DateTime.Now);

            //assert
            Assert.AreEqual(3, res.Count);
        }
        internal void Run()
        {
            IFileManager    fileManager    = new FileManager();
            IReceiptManager receiptManager = new ReceiptManager();

            List <string> inputs = new List <string>();

            int counter = 1;

            Console.WriteLine("Input");

            while (true)
            {
                string input = fileManager.LoadInputFromResourceFile($"input_{counter}.txt");

                if (string.IsNullOrEmpty(input))
                {
                    break;
                }

                Console.WriteLine($"{Constants.SingleIndentation}Shopping Basket {counter}:");
                PrintLinesWithIndentation(input);
                inputs.Add(input);
                counter++;
            }

            counter = 1;

            Console.WriteLine("Output");

            foreach (var input in inputs)
            {
                string result = receiptManager.GenerateReceipt(input);

                Console.WriteLine($"{Constants.SingleIndentation}Output {counter}:");
                PrintLinesWithIndentation(result);
                counter++;
            }
        }
예제 #15
0
    /// <summary>
    /// Carrega os items que vem do banco na lista em memória, lista essa que popula a grid
    /// </summary>
    private void LoadReceiptItems()
    {
        List <ReceiptItem> loadedReceiptItems =
            ReceiptManager.GetReceiptItemsAsList(Company.CompanyId, Original_Receipt.ReceiptId);

        foreach (ReceiptItem item in loadedReceiptItems)
        {
            if (item.ProductId.HasValue)
            {
                AddReceiptItem(item.Product, item);
            }
            else if (item.ServiceId.HasValue)
            {
                AddReceiptItem(item.Service, item);
            }
            else
            {
                AddReceiptItem((Product)null, item);
            }
        }
        BindReceiptItems();
    }
예제 #16
0
        //檢查發票號碼
        public static string checkReceiptNumber(string receiptNumber)
        {
            string label;
            var    manager = new ReceiptManager();

            if (receiptNumber == null || receiptNumber.Length == 0)
            {
                label = "發票編號不能為空";
            }
            else if (receiptNumber.Length != 11 || !Regex.IsMatch(receiptNumber, @"^[A-Z]{2}[-]{1}[0-9]{8}$"))
            {
                label = "發票格式不正確";
            }
            else if (HttpContext.Current.Request.QueryString["RepNo"] == null && manager.GetReceipt(receiptNumber) != null)
            {
                label = "此發票號碼重複";
            }
            else
            {
                label = string.Empty;
            }
            return(label);
        }
예제 #17
0
    public static bool DeleteReceipt(int receiptId, int companyId)
    {
        bool result = true;

        var sale = new SaleManager(null).GetSaleByReceipt(companyId, receiptId);

        if (sale != null)
        {
            new SaleManager(null).SetNullReceiptIDInSale(sale.SaleId);
        }

        using (ReceiptManager receiptManager = new ReceiptManager(null))
        {
            try
            {
                receiptManager.DeleteReceipt(receiptManager.GetReceipt(receiptId, companyId));
            }
            catch (System.Data.SqlClient.SqlException)
            {
                result = false;
            }
        }
        return(result);
    }
 public void Setup()
 {
     this.appleHttpRequestMock = new Mock <IAppleHttpRequest>();
     this.receiptManager       = new ReceiptManager(this.appleHttpRequestMock.Object);
 }
 public ReceiptsController(ReceiptManager receiptManager, OrderManager orderManager, RestaurantManager restaurantManager)
 {
     _receiptManager    = receiptManager;
     _orderManager      = orderManager;
     _restaurantManager = restaurantManager;
 }
        /// <summary>
        /// This method cancels a sale and return the products to inventory
        /// </summary>
        /// <param name="saleId"></param>
        /// <param name="matrixId"></param>
        public void CancelSale(int saleId, int matrixId, Int32 userId)
        {
            var inventoryManager = new InventoryManager(this);
            var receiptManager = new ReceiptManager(this);
            var financialManager = new FinancialManager(this);
            var parcelManager = new ParcelsManager(this);

            Sale sale = GetSale(matrixId, saleId);
            sale.IsCanceled = true;

            if (sale.ReceiptId != null)
            {
                Receipt receipt = receiptManager.GetReceipt((int)sale.ReceiptId, sale.CompanyId);
                sale.ReceiptId = null;
                receiptManager.DeleteReceipt(receipt);
                receipt.IsCanceled = true;
            }

            sale.InvoiceId = null;

            //
            // return the products to inventory
            //
            foreach (SaleItem saleItem in sale.SaleItems)
            {
                if (saleItem.ProductId != null)
                {
                    Inventory inventory = inventoryManager.GetProductInventory(saleItem.CompanyId,
                                                                               (int)saleItem.ProductId,
                                                                               (int)sale.DepositId);
                    if (inventory != null)
                        inventoryManager.StockDeposit(inventory, null, userId);
                }
            }

            //
            // Delete the invoice of sale
            //
            if (sale.InvoiceId.HasValue)
                financialManager.DeleteInvoice((int)sale.InvoiceId, sale.CompanyId);

            DbContext.SubmitChanges();
        }
예제 #21
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        btnSave.Focus();
        var receipt = new Receipt();
        var lstSavingReceiptItem = new List <ReceiptItem>();

        if (!ReceiptItems.Any())
        {
            ShowError(Exception.UnselectedItem);
            return;
        }

        UpdateReceiptValue();

        if (IsLoaded)
        {
            receipt.CopyPropertiesFrom(Original_Receipt);
        }

        receipt.SubstitutionICMSBase  = ucCurrFieldSubstituionICMSBase.CurrencyValue;
        receipt.SubstitutionICMSValue = ucCurrFieldSubstituionICMSValue.CurrencyValue;
        receipt.FreightValue          = ucCurrFieldFreightValue.CurrencyValue;
        receipt.InsuranceValue        = ucCurrFieldInsuranceValue.CurrencyValue;
        receipt.OthersChargesValue    = ucCurrFieldOthersChargesValue.CurrencyValue;


        if (!String.IsNullOrEmpty(lblReceiptValue.Text))
        {
            receipt.ReceiptValue = Convert.ToDecimal(lblReceiptValue.Text.Replace("_", ""));
        }

        receipt.CompanyId = Company.CompanyId;

        if (Page.ViewState["customerId"] != null)
        {
            receipt.SupplierId = null;
            receipt.CustomerId = Convert.ToInt32(Page.ViewState["customerId"]);
        }
        else
        {
            receipt.CustomerId = null;
            receipt.SupplierId = Convert.ToInt32(Page.ViewState["SupplierId"]);
        }
        if (Page.ViewState["TransporterId"] != null)
        {
            receipt.TransporterId = Convert.ToInt32(Page.ViewState["TransporterId"]);
        }

        receipt.DeliveryDate = null;
        receipt.EntryDate    = null;

        if (ucEntrydate.DateTime.HasValue)
        {
            receipt.EntryDate = ucEntrydate.DateTime;
        }
        else
        {
            receipt.DeliveryDate = ucDeliveryDate.DateTime;
        }

        if (ucIssueDate.DateTime.HasValue)
        {
            receipt.IssueDate = ucIssueDate.DateTime.Value;
        }

        receipt.CfopId = Convert.ToInt32(cboCFOP.SelectedValue);

        receipt.ReceiptNumber = ucCurrFieldReceiptNumber.IntValue;

        foreach (ReceiptItem item in ReceiptItems)
        {
            item.ReceiptId = receipt.ReceiptId;
            lstSavingReceiptItem.Add(item);
        }

        try
        {
            ///update ReceiptValue
            ReceiptManager.SaveReceipt(Original_Receipt, receipt, lstSavingReceiptItem, LstServiceOrder, LstSale);
        }
        catch (InvalidOperationException)
        {
            ShowError(Exception.InvalidReceiptNumber);
            return;
        }
        Server.Transfer("Receipts.aspx");
    }
 public ReceiptHandler()
 {
     receiptManager = new ReceiptManager();
 }
 public ClientResponse FindProductAndService(String q, Int32 limit)
 {
     return new ClientResponse(() =>
     {
         using (var receiptManager = new ReceiptManager(null))
             return receiptManager.SearchProductAndService((Int32)Company.MatrixId, q, limit).ToArray();
     });
 }
예제 #24
0
        private void LoadRepeater()
        {
            string page   = Request.QueryString["Page"];
            int    pIndex = 0;

            if (string.IsNullOrEmpty(page))
            {
                pIndex = 1;
            }
            else
            {
                int.TryParse(page, out pIndex);

                if (pIndex <= 0)
                {
                    pIndex = 1;
                }
            }

            string company      = Request.QueryString["company"];
            string minPriceText = Request.QueryString["minPrice"];
            string maxPriceText = Request.QueryString["maxPrice"];
            string R_EText      = Request.QueryString["R_E"];

            decimal?minPrice = null;
            decimal?maxPrice = null;

            if (!string.IsNullOrEmpty(minPriceText))
            {
                int temp;
                if (int.TryParse(minPriceText, out temp))
                {
                    minPrice = temp;
                }
            }

            if (!string.IsNullOrEmpty(maxPriceText))
            {
                int temp;
                if (int.TryParse(maxPriceText, out temp))
                {
                    maxPrice = temp;
                }
            }

            int?R_E = null;

            if (!string.IsNullOrEmpty(R_EText))
            {
                int temp;
                if (int.TryParse(R_EText, out temp))
                {
                    R_E = temp;
                }
            }

            int totalSize = 0;

            var manager = new ReceiptManager();
            var list    = manager.GetReceipts(company, minPrice, maxPrice, R_E, out totalSize, pIndex, _pageSize);

            this.repInvoice.DataSource = list;
            this.repInvoice.DataBind();

            var pagination = new PagingHelper();
            int pages      = pagination.CalculatePages(totalSize, _pageSize);

            this.firstPage.HRef = pagination.GetPageUrl(1);
            this.lastPage.HRef  = pagination.GetPageUrl(pages);
            var pagingList = pagination.RepPagingList(pages);

            this.repPaging.DataSource = pagingList;
            this.repPaging.DataBind();

            this.lblCurrentPage.Text = pIndex.ToString();
            this.lblTotalPage.Text   = pages.ToString();
        }
 // GET: ReceiptItem
 public ActionResult DisplayForReceipt(int id)
 {
     ViewBag.receipt = ReceiptManager.Get(id);
     return(View(ReceiptItemManager.GetAllForReceipt(id)));
 }
예제 #26
0
        //[HttpPost]
        public ActionResult AppStore(Dictionary <string, string> queryvalues)
        {
//#if Debug
//            queryvalues = new Dictionary<string, string>();
//            queryvalues.Add("transtime", "1472653281");
//            queryvalues.Add("productid", "Chip_3");
//            queryvalues.Add("identityid", "403278");
//            queryvalues.Add("othertype", "2");
//            queryvalues.Add("other", "8B58253C-9B85-4D13-93EF-0F9D21162895");
//            queryvalues.Add("customsign", "7fa5c658db8804a14879c972f271d58d");

//            queryvalues.Add("transactionid", "440000246529282");
//            queryvalues.Add("isfirstrecharge", "0");
//            queryvalues.Add("transactionreceipt", "ewoJInNpZ25hdHVyZSIgPSAiQXhvZGJkQlFNWnBVUkhKbXQvdWw4MExza2RuWDZlaXVzaGl4ZzI4WFNOM0ROZTdBbFp3K2NPVDhENEo5Q0dUMlJUS0d4TlZCeVFnRjNzb3YrL2FISS9VWEZUL29rMUhtVXowcmRSVmhzaTErUmFvdVdDNmpqNzUydGR0WTQzb3FhQ0pPcnJ1VCs1ckI1VTl0aXFwNVRJR1BEbnRVTzhkeERuM2MwVjM0Qk5JcWt5aUQ4UmlOd1M3ZW55Wk04RkUxeGtMWm56ZW82MjNXRU9tU0Y2QTVVK2ZHMDBRQlcvUysweGZhUEU1TjN4WEk4bzVFNDl0UXlybUVRUWFKVGhBWFJLamJqMjJOTlRDMkZML0tOM2M1eU1mNkkrVU9WcE1sREUxZUVxalhOREZVRmZYYmFWVHJVaEtKTmo1Y1BWZ2Jid0laeW1kZlFpZU9rSzcwNDdvVU0vVUFBQVdBTUlJRmZEQ0NCR1NnQXdJQkFnSUlEdXRYaCtlZUNZMHdEUVlKS29aSWh2Y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EyWlc1a2IzSXRhV1JsYm5ScFptbGxjaUlnUFNBaU1VTkJOVVkyUlRBdE1FVkVPQzAwTkVZeExUazRNVE10T1VNNE9ERXlNa1E1UXpoQklqc0tDU0pwZEdWdExXbGtJaUE5SUNJeE1EVTBNekl4T1RnMElqc0tDU0oyWlhKemFXOXVMV1Y0ZEdWeWJtRnNMV2xrWlc1MGFXWnBaWElpSUQwZ0lqZ3hPRFUxTnpRM09TSTdDZ2tpY0hKdlpIVmpkQzFwWkNJZ1BTQWlkM2wzWDBOb2FYQmZPQ0k3Q2draWNIVnlZMmhoYzJVdFpHRjBaU0lnUFNBaU1qQXhOaTB3T0Mwek1TQXhORG95TVRveE9TQkZkR012UjAxVUlqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURFMkxUQTRMVE14SURFME9qSXhPakU1SUVWMFl5OUhUVlFpT3dvSkltSnBaQ0lnUFNBaVkyOXRMbWRoYldVMU1UVXVkM2wzWkdWNmFHOTFJanNLQ1NKd2RYSmphR0Z6WlMxa1lYUmxMWEJ6ZENJZ1BTQWlNakF4Tmkwd09DMHpNU0F3TnpveU1Ub3hPU0JCYldWeWFXTmhMMHh2YzE5QmJtZGxiR1Z6SWpzS2ZRPT0iOwoJInBvZCIgPSAiNDQiOwoJInNpZ25pbmctc3RhdHVzIiA9ICIwIjsKfQ==");
//#endif



            string _transtime  = queryvalues.ContainsKey("transtime") ? queryvalues["transtime"] : string.Empty;
            string _productid  = queryvalues.ContainsKey("productid") ? queryvalues["productid"] : string.Empty;
            int    _identityid = queryvalues.ContainsKey("identityid") ? Convert.ToInt32(queryvalues["identityid"]) : 0;
            int    _othertype  = queryvalues.ContainsKey("othertype") ? Convert.ToInt32(queryvalues["othertype"]) : 0;
            string _other      = queryvalues.ContainsKey("other") ? queryvalues["other"] : string.Empty;
            string _customSign = queryvalues.ContainsKey("customsign") ? queryvalues["customsign"] : string.Empty;

            string Key = _key;

            string _transactionid      = queryvalues.ContainsKey("transactionid") ? queryvalues["transactionid"] : string.Empty;
            int    _isfirstrecharge    = queryvalues.ContainsKey("isfirstrecharge") ? Convert.ToInt32(queryvalues["isfirstrecharge"]) : 0;
            string _transactionreceipt = queryvalues.ContainsKey("transactionreceipt") ? queryvalues["transactionreceipt"] : string.Empty;
            string md5 = Utils.MD5(string.Concat(_transtime, _identityid, _othertype, _other, _productid, Key));

            if (!_customSign.Equals(md5))
            {
                log.Error("AppStore 参数不正确");
                return(Json(new { result = 10001, msg = "AppStore 参数不正确" }));
            }


            //Convert.FromBase64String(System.Text.Encoding.ASCII.GetBytes(_transactionreceipt))
            var res = System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(_transactionreceipt));

            //(JObject)JsonConvert.DeserializeObject


            ReceiptManager receiptManager = new ReceiptManager();
            var            env            = Environments.Production;



            if (res.IndexOf("Sandbox") > 0)
            {
                env = Environments.Sandbox;
            }



            var response = receiptManager.ValidateReceipt(env, res);

            log.Info("response.Status=" + response.Status);
            log.Info("Environments.Sandbox" + res.IndexOf("Sandbox"));


            if (response.Status > 0)
            {
                log.Error("AppStore ReceiptVerifier Error Status :" + response.Status);
                return(Json(new { result = response.Status }));
            }


            if (!(response.Receipt.BundleIdentifier == "com.game515.wywdezhou" || response.Receipt.BundleIdentifier == "com.game515.515dezhou" || response.Receipt.BundleIdentifier == "com.gamehk.wanrendezhou" || response.Receipt.BundleIdentifier == "com.gamehk.wanrenqlunpan"))
            {
                log.Error("AppStore ReceiptVerifier Error bid :" + response.Receipt.BundleIdentifier);
                return(Json(new { result = 10006, msg = "AppStore ReceiptVerifier Error bid :" + response.Receipt.BundleIdentifier }));
            }


            try
            {
                //RechargeCheck rc = RechargeCheckBLL.GetModelBySerialNo(new RechargeCheck { SerialNo = out_trade_no });

                //if (rc == null)
                //{
                //    log.Error(" AppStore 订单[" + out_trade_no + "]不存在");
                //    return Content("fail");
                //}
                Recharge rc = RechargeBLL.GetModelByBillNo(new Recharge {
                    BillNo = _transactionid
                });
                if (rc != null)
                {
                    log.Error(" AppStore 订单[" + _transactionid + "]已存在");
                    return(Json(new { result = 1, msg = "AppStore 订单[" + _transactionid + "]已存在" }));
                }


                Role user = RoleBLL.GetModelByID(new Role {
                    ID = _identityid
                });
                if (user == null)
                {
                    log.Error(" AppStore 用户[" + _identityid + "]不存在");
                    return(Json(new { result = 10002, msg = "AppStore 用户[" + _identityid + "]不存在" }));
                }
                IAPProduct iap = IAPProductBLL.GetModelByID(_productid);
                if (iap == null)
                {
                    log.Error(" AppStore 支付配表出错");
                    return(Json(new { result = 10003, msg = "AppStore 支付配表出错" }));
                }


                isFirst  iF = iap.product_id.Split('_')[0].Equals("firstCharge") ? isFirst.是 : isFirst.否;
                chipType ct = iF == isFirst.是 ? chipType.首冲礼包 : (chipType)iap.goodsType;



                bool firstGif = iF == isFirst.是;



                Recharge recharge = RechargeBLL.GetFirstModelListByUserID(new Recharge {
                    UserID = _identityid
                });
                if (recharge != null)//首冲过
                {
                    if (firstGif == true)
                    {//又是首冲,则改变其为不首冲
                        firstGif      = false;
                        ct            = (chipType)1;
                        iF            = isFirst.否;
                        iap.goodsType = 1;
                        log.Error(" 多次首冲,修改firstGif值");
                    }
                }

                RechargeCheckBLL.AddOrderIP(new UserIpInfo {
                    UserID = _identityid, OrderID = _transactionid, CreateTime = DateTime.Now, ChargeType = (int)raType.AppStore, OrderIP = GetClientIp()
                });
                RechargeIP ipmodel = GetCallBackClientIp();
                RechargeCheckBLL.AddCallBackOrderIP(new UserIpInfo {
                    CallBackUserID = _identityid, OrderID = _transactionid, Method = ipmodel.Method, CallBackIP = ipmodel.IP, CallBackTime = DateTime.Now, CallBackChargeType = (int)raType.AppStore
                });



                uint gold = iap.goodsType == 1 ? (uint)iap.goods : 0;
                uint dia  = iap.goodsType == 2 ? (uint)iap.goods : 0;
                if (firstGif)
                {
                    gold = (uint)(iap.goods + iap.attach_chip);
                    dia  = (uint)iap.attach_5b;
                }
                string list = iap.attach_props;
                list = list.Trim(',') + (gold > 0 ? ",10000:" + gold + "," : "");
                list = list.Trim(',') + (dia > 0 ? ",20000:" + dia + "," : "");
                list = list.Trim(',') + ",";
                uint rmb = (uint)iap.price;
                log.Info(" 分 :" + rmb * 100);
                // rmb = rmb * 100;//将元单位转换为分的单位转给游戏服务器



                RechargeBLL.Add(new Recharge {
                    BillNo = _transactionid, OpenID = response.Receipt.UniqueIdentifier, UserID = _identityid, Money = (rmb * 100), CreateTime = DateTime.Now, Chip = gold, Diamond = dia, ChipType = ct, IsFirst = iF, NickName = iap.productname, PayItem = iap.product_id, PF = raType.AppStore, UserAccount = user.NickName, ActualMoney = (rmb * 100), ProductNO = list.Trim(',')
                });


                log.Info(" 开始给服务器发送消息_identityid=" + _identityid + ",list=" + list + ",rmb*100=" + rmb * 100 + ",firstGif=" + firstGif + ",_transactionid=" + _transactionid);


                normal ServiceNormalS = normal.CreateBuilder()
                                        .SetUserID((uint)_identityid)
                                        .SetList(list)
                                        .SetRmb(rmb * 100)//将元单位转换为分的单位转给游戏服务器
                                        .SetRmbActual(rmb * 100)
                                        .SetFirstGif(firstGif)
                                        .SetBillNo(_transactionid)
                                        .Build();

                Bind tbind = Cmd.runClient(new Bind(BR_Cmd.BR_NORMAL, ServiceNormalS.ToByteArray()));
                switch ((CenterCmd)tbind.header.CommandID)
                {
                case CenterCmd.CS_NORMAL:


                    log.Info("CenterCmd.CS_NORMAL:");

                    normalRep ServiceNormalC = normalRep.ParseFrom(tbind.body.ToBytes());
                    log.Info(" AppStore ServiceResult : " + ServiceNormalC.Suc);
                    if (ServiceNormalC.Suc)
                    {
                        log.Info(" AppStore ServiceResult [" + _transactionid + "] : " + ServiceNormalC.Suc);

                        RechargeBLL.UpdateReachTime(_transactionid);
                        //RechargeCheckBLL.Delete(new RechargeCheck { SerialNo = rc.SerialNo });
                    }

                    //Response.Redirect("mobilecall://fail?suc=" + ServiceNormalC.Suc);
                    break;

                case CenterCmd.CS_CONNECT_ERROR:


                    log.Info(" CenterCmd.CS_CONNECT_ERROR:");


                    break;
                }


                log.Info(" AppStore Process Success[" + _transactionid + "]: " + Utils.GetUrl() + "?" + Core.CreateLinkStringUrlencode(queryvalues, Encoding.UTF8));

                return(Json(new
                {
                    result = 0,
                    productid = _productid,
                    transactionid = _transactionid,
                    isfirstrecharge = _isfirstrecharge
                }));


                //log.Error(" AppStore fail : q " + Utils.GetUrl() + Utils.CreateLinkStringUrlencode(queryvalues, Encoding.UTF8));
                //return Json(new { result = 10004, msg = "AppStore 服务器发货失败" });
            }
            catch (Exception err)
            {
                log.Error(" AppStore fail : q " + Utils.GetUrl() + Utils.CreateLinkStringUrlencode(queryvalues, Encoding.UTF8), err);
                return(Json(new { result = 10005, msg = "AppStore 服务器发货失败 err:" + err.Message }));
            }
        }
예제 #27
0
    public static bool DeleteReceipt(int receiptId, int companyId)
    {

        bool result = true;

        var sale = new SaleManager(null).GetSaleByReceipt(companyId, receiptId);

        if (sale != null)
            new SaleManager(null).SetNullReceiptIDInSale(sale.SaleId);

        using (ReceiptManager receiptManager = new ReceiptManager(null))
        {
            try
            {
                receiptManager.DeleteReceipt(receiptManager.GetReceipt(receiptId, companyId));
            }
            catch (System.Data.SqlClient.SqlException)
            {
                result = false;
            }
        }
        return result;
    }