public ActionResult AddPurchase(int id) { Purchase purchase = new Purchase(); { purchase.CreateDate = DateTime.Now; purchase.Id = 1; } decimal k = 0; //foreach (var find in products) //{ // //if (find.CartId == id) // //{ // // k = k + find.Price; // //} //} //purchase.TotalPrice = k; //purchases.Add(purchase); return View(purchase); }
public IHttpActionResult CreatePurchase(int id) { var userId = this.User.Identity.GetUserId(); var book = this.Data.Books.Read().FirstOrDefault(b => b.Id == id); if (book == null) { return this.NotFound(); } if (book.Copies == 0) { return this.BadRequest("There are no copies left."); } var purchase = new Purchase { UserId = userId, Book = book, Price = book.Price, DateOfPurchase = DateTime.Now, IsRecalled = false }; this.Data.Purchases.Create(purchase); book.Copies--; this.Data.SaveChanges(); return this.Ok("Your purchase number is: " + purchase.Id); }
private static void HandlerOnOnPurchaseFailedValidation(Purchase purchase, string purchaseData, string purchaseSignature) { var message = string.Format("Id={0}, developerPayload={1}, state={2}, orderId={3}, time={4}, data={5}", purchase.ProductId, purchase.DeveloperPayload, purchase.PurchaseState, purchase.OrderId, purchase.PurchaseTime, purchaseData); GaService.TrackAppException("Extensions", "HandlerOnOnPurchaseFailedValidation", string.Empty, message, false); }
public ViewEditPurchaseView(Purchase thisPurchase) { InitializeComponent(); _currentPurchase = thisPurchase; this.Text = string.Format("Purchase No. {0:0000}", _currentPurchase); InitializeThings(); }
public void EntitiesTest() { Purchase purchase = new Purchase() { Id = 1 }; purchase.PurchaseLine.Add(new PurchaseLine() { Id = 1, Purchase = purchase }); purchase.PurchaseLine.Add(new PurchaseLine() { Id = 2, Purchase = purchase }); StringWriter sw = new StringWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; using (JsonWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; serializer.Serialize(jw, purchase); } string json = sw.ToString(); Assert.AreEqual(@"{ ""Id"": 1, ""PurchaseLine"": [ { ""Id"": 1, ""PurchaseReference"": { ""EntityKey"": null, ""RelationshipName"": ""EntityDataModel.PurchasePurchaseLine"", ""SourceRoleName"": ""PurchaseLine"", ""TargetRoleName"": ""Purchase"", ""RelationshipSet"": null, ""IsLoaded"": false }, ""EntityState"": 1, ""EntityKey"": null }, { ""Id"": 2, ""PurchaseReference"": { ""EntityKey"": null, ""RelationshipName"": ""EntityDataModel.PurchasePurchaseLine"", ""SourceRoleName"": ""PurchaseLine"", ""TargetRoleName"": ""Purchase"", ""RelationshipSet"": null, ""IsLoaded"": false }, ""EntityState"": 1, ""EntityKey"": null } ], ""EntityState"": 1, ""EntityKey"": null }", json); Purchase newPurchase = JsonConvert.DeserializeObject<Purchase>(json); Assert.AreEqual(1, newPurchase.Id); Assert.AreEqual(2, newPurchase.PurchaseLine.Count); Assert.AreEqual(1, newPurchase.PurchaseLine.ElementAt(0).Id); Assert.AreEqual(2, newPurchase.PurchaseLine.ElementAt(1).Id); }
static void Main(string[] args) { //объявление и инициализация массива Purchase[] purchases = new Purchase[] { new Purchase("cup",38000,3,Days.Mon), new Purchase("plate",50000,1,Days.Sun), new Purchase("spoon",21000,4,Days.Wed), new Purchase("fork",12000,4,Days.Fri), new Purchase("knife",35000,2,Days.Sat), }; double sum = 0; // переменная для нахождения суммы покупок for (int i = 0; i < purchases.Length; i++) { if (purchases[i] != null) { Console.WriteLine(purchases[i]); sum = sum + purchases[i].GetCost(); } } Array.Sort(purchases); Console.WriteLine("\nСредняя стоимость всех покупок "+(sum/purchases.Length)); Console.WriteLine("День самой дорогой покупки " + purchases[0].Days+"\n"); for (int i = 0; i < purchases.Length; i++) { if (purchases[i] != null) Console.WriteLine(purchases[i]); } Console.ReadKey(); }
public static Purchase CreateFromSku(string sku, string developerPayload) { var p = new Purchase(); p.Sku = sku; p.DeveloperPayload = developerPayload; return p; }
public ReceiptModel BasicPurchase(RequestModel model) { OrderInfo oinfo = new OrderInfo(); string host = AuthInfo.Host; string store_id = AuthInfo.StoreID; string api_token = AuthInfo.APIToken; string order_id = oinfo.GenerateOrderID();// "Test_P_0333"; string amount = model.Amount.Value.ToString(); string pan = model.PAN;// "4242424242424242"; string expdate = model.ExpDate.ToString();//"0812"; string crypt = model.Crypt;// "7"; //string status = "true"; /* Status Check Example */ // HttpsPostRequest mpgReq = // new HttpsPostRequest(host, store_id, api_token, status, // new Purchase(order_id, amount, pan, expdate, crypt)); Purchase purchase = new Purchase(order_id, amount, pan, expdate, crypt); //purchase.SetDynamicDescriptor("2134565"); HttpsPostRequest mpgReq = new HttpsPostRequest(host, store_id, api_token, purchase); ReceiptModel rcptModel = new ReceiptModel(); try { Receipt receipt = mpgReq.GetReceipt(); rcptModel.CardType = receipt.GetCardType(); rcptModel.TransAmount =receipt.GetTransAmount(); rcptModel.TxnNumber = receipt.GetTxnNumber(); rcptModel.ReceiptId = receipt.GetReceiptId(); rcptModel.TransType = receipt.GetTransType(); rcptModel.ReferenceNum = receipt.GetReferenceNum(); rcptModel.ResponseCode = receipt.GetResponseCode(); rcptModel.ISO = receipt.GetISO(); rcptModel.BankTotals = receipt.GetBankTotals(); rcptModel.Message = receipt.GetMessage(); rcptModel.AuthCode = receipt.GetAuthCode(); rcptModel.Complete = receipt.GetComplete(); rcptModel.TransDate = receipt.GetTransDate(); rcptModel.TransTime = receipt.GetTransTime(); rcptModel.Ticket = receipt.GetTicket(); rcptModel.TimedOut = receipt.GetTimedOut(); rcptModel.IsVisaDebit = receipt.GetIsVisaDebit(); //Console.WriteLine("StatusCode = " + receipt.GetStatusCode()); //Console.WriteLine("StatusMessage = " + receipt.GetStatusMessage()); return rcptModel; } catch (Exception e) { Console.WriteLine(e); return null; } }
// // GET: /Purchase/Create public ActionResult Create() { Purchase p = new Purchase(); p.TimeStamp = DateTime.Now; p.VAT = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["DefaultVAT"]); ViewBag.ProviderID = new SelectList(db.Providers.OrderBy(pr => pr.Name), "ProviderID", "Name"); ViewBag.PurchaseTypeID = new SelectList(db.PurchaseTypes.OrderBy(et=>et.Name), "PurchaseTypeID", "Name"); return View(p); }
public bool ConsumePurchase(Purchase purchase) { if (purchase == null) { throw new ArgumentNullException("purchase"); } return ConsumePurchase(purchase.PurchaseToken); }
public string Buy(Purchase purchase) { purchase.Date = DateTime.Now; purchase.Subject = "Technics"; // добавляем информацию о покупке в базу данных dbTechnics.Purchases.Add(purchase); // сохраняем в бд все изменения dbTechnics.SaveChanges(); return "Спасибо за покупку!"; }
public string Buy(Purchase purchase) { purchase.Date = DateTime.Now; purchase.Subject = "Books"; // добавляем информацию о покупке в базу данных Repository.dbBooks.Purchases.Add(purchase); // сохраняем в бд все изменения Repository.dbBooks.SaveChanges(); return "Спасибо, за покупку!"; }
public static Purchase CreateFromSku(string sku, string developerPayload) { var p = new Purchase(); p.Sku = sku; p.DeveloperPayload = developerPayload; #if UNITY_IOS AddIOSHack(p); #endif return p; }
public SaleDetailsWindow(Purchase purch) { InitializeComponent(); lblHeader.Text = purch.User.Username; lblDate.Text = "Datum:\t" + purch.Date.ToString(); lblCount.Text = "Anzahl:\t" + purch.Count.ToString(); lblAmount.Text = "Summe:\t" + string.Format("{0:0.00 €}", purch.Amount); dgvArticles.ItemsSource = purch.Articles; }
public static void Main(string[] args) { string host = "esqa.moneris.com"; string store_id = "store5"; string api_token = "yesguy"; string order_id = "Test_P_0333"; string amount = "5.00"; string pan = "4242424242424242"; string expdate = "0812"; string crypt = "7"; //string status = "true"; /* Status Check Example */ // HttpsPostRequest mpgReq = // new HttpsPostRequest(host, store_id, api_token, status, // new Purchase(order_id, amount, pan, expdate, crypt)); Purchase purchase = new Purchase(order_id, amount, pan, expdate, crypt); //purchase.SetDynamicDescriptor("2134565"); HttpsPostRequest mpgReq = new HttpsPostRequest(host, store_id, api_token, purchase); try { Receipt receipt = mpgReq.GetReceipt(); Console.WriteLine("CardType = " + receipt.GetCardType()); Console.WriteLine("TransAmount = " + receipt.GetTransAmount()); Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber()); Console.WriteLine("ReceiptId = " + receipt.GetReceiptId()); Console.WriteLine("TransType = " + receipt.GetTransType()); Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum()); Console.WriteLine("ResponseCode = " + receipt.GetResponseCode()); Console.WriteLine("ISO = " + receipt.GetISO()); Console.WriteLine("BankTotals = " + receipt.GetBankTotals()); Console.WriteLine("Message = " + receipt.GetMessage()); Console.WriteLine("AuthCode = " + receipt.GetAuthCode()); Console.WriteLine("Complete = " + receipt.GetComplete()); Console.WriteLine("TransDate = " + receipt.GetTransDate()); Console.WriteLine("TransTime = " + receipt.GetTransTime()); Console.WriteLine("Ticket = " + receipt.GetTicket()); Console.WriteLine("TimedOut = " + receipt.GetTimedOut()); Console.WriteLine("IsVisaDebit = " + receipt.GetIsVisaDebit()); //Console.WriteLine("StatusCode = " + receipt.GetStatusCode()); //Console.WriteLine("StatusMessage = " + receipt.GetStatusMessage()); } catch (Exception e) { Console.WriteLine(e); } }
public override void ProcessRequest(Purchase purchase) { if (purchase.Amount < 100000.0) { Console.WriteLine($"{this.GetType().Name} approved request #{purchase.Number}"); } else { Console.WriteLine($"Request {purchase.Number} requires an executive meeting"); } }
public override void ProcessRequest(Purchase purchase) { if (purchase.Amount < 10000.0) { Console.WriteLine("{0} approved request# {1} for {2}", this.GetType().Name, purchase.Number, purchase.Purpose); } else if (successor != null) { successor.ProcessRequest(purchase); } }
private static void AddIOSHack(Purchase p) { if(string.IsNullOrEmpty(p.AppstoreName)) { p.AppstoreName = "com.apple.appstore"; } if(string.IsNullOrEmpty(p.ItemType)) { p.ItemType = "InApp"; } if(string.IsNullOrEmpty(p.OrderId)) { p.OrderId = System.Guid.NewGuid().ToString(); } }
public override Enums.ApprovalResponse ProcessRequest(Purchase purchase) { if (purchase.Amount < 50000) { return Enums.ApprovalResponse.Approved; } else { return _successor.ProcessRequest(purchase); } }
public override void ProcessRequest(Purchase purchase) { if (purchase.Amount < 1000.0) { Console.WriteLine($"{this.GetType().Name} approved request #{purchase.Number}"); } else if(this.Successor != null) { this.Successor.ProcessRequest(purchase); } }
public ActionResult Create(Purchase purchase) { if (ModelState.IsValid) { db.Purchases.Add(purchase); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ProviderID = new SelectList(db.Providers.OrderBy(p => p.Name), "ProviderID", "Name", purchase.ProviderID); ViewBag.PurchaseTypeID = new SelectList(db.PurchaseTypes.OrderBy(et => et.Name), "PurchaseTypeID", "Name"); return View(purchase); }
internal static PurchaseEntity Purchase(Purchase ent) { PurchaseEntity data = new PurchaseEntity(); data.purchaseId = ent.Id; data.itemFK = ent.ItemFK; data.purchaserFK = ent.PurchaserFK; data.purchaseDate = ent.PurchaseDate; data.updateTimestamp = ent.UpdateTimestamp; data.updatePersonFK = ent.UpdatePersonFK; return data; }
public AddEditPurchaseView(Purchase purchase = null) { InitializeComponent(); _currentPurchase = purchase ?? new Purchase { DateRecorded = DateTime.Now, CreatedByUserID = CurrentlyLoggedInUser.UserID, Status = BuzzleEnums.PurshaseStatuses.Awaiting_Purchase.ToString() }; Initialize(); }
internal static Purchase Purchase(PurchaseEntity data) { Purchase ent = new Purchase(); ent.Id = data.purchaseId; ent.ItemFK = data.itemFK; ent.PurchaserFK = data.purchaserFK; ent.PurchaseDate = data.purchaseDate; ent.UpdateTimestamp = data.updateTimestamp; ent.UpdatePersonFK = data.updatePersonFK; return ent; }
private void purchaseSucceededEvent(Purchase purchase) { if (_player != null) { _player.GetComponent<HeroControll>().PlayerRevive(); OpenIAB.consumeProduct(purchase); } else { _player = GameObject.FindWithTag("Player").GetComponent<GameEntity>(); _player.GetComponent<HeroControll>().PlayerRevive(); OpenIAB.consumeProduct(purchase); } Mixpanel.SendEvent(AnalyticsEvents.PURCHASE_HEALTH); }
public override void ProcessRequest(Purchase purchase) { if (purchase.Amount < 100000.0) { Console.WriteLine( "{0} approved request #{1}", this.GetType().Name, purchase.Number); } else { // Pokupkata e prekaleno goliama i izsikva da se svika borda na direktorite. Console.WriteLine( "Request #{0} requires an executive meeting!", purchase.Number); } }
private static void Main() { var larry = new Director(); var sam = new VicePresident(); var tammy = new President(); larry.SetSuccessor(sam); sam.SetSuccessor(tammy); var purchase = new Purchase(1231, 350.0, "Assets"); larry.ProcessRequest(purchase); purchase = new Purchase(321, 12313.123, "Project X"); larry.ProcessRequest(purchase); purchase = new Purchase(123123, 123123123.123, "Project Y"); larry.ProcessRequest(purchase); }
internal static void Main() { Approver teamLead = new TeamLead(); Approver vp = new VicePresident(); Approver ceo = new President(); teamLead.SetSuccessor(vp); vp.SetSuccessor(ceo); var purchase = new Purchase(2034, 350.00); teamLead.ProcessRequest(purchase); purchase = new Purchase(2035, 32590.10); teamLead.ProcessRequest(purchase); purchase = new Purchase(2036, 122100.00); teamLead.ProcessRequest(purchase); }
public void OnPurchaseSucceeded(Purchase purchase) { if (AudioManager.instance.sfxEnabled) this.GetComponent<AudioSource>().Play(); Debug.Log("OnPurchaseSucceeded"); OpenIAB.consumeProduct(purchase); ValidateGooglePlayPurchaseRequest request = new ValidateGooglePlayPurchaseRequest(); request.ReceiptJson = purchase.OriginalJson; request.Signature = purchase.Signature; PlayFabClientAPI.ValidateGooglePlayPurchase(request, OnValidateCompleted, OnValidateError); // calling this before validation? UpdateUserDataRequest dataRequest = new UpdateUserDataRequest(); dataRequest.Data = new Dictionary<string, string>(); dataRequest.Data.Add(GameConstants.boughtSheKey, "true"); dataRequest.Permission = UserDataPermission.Public; PlayFabClientAPI.UpdateUserData(dataRequest, OnDataUpdateCompleted, OnDataUpdateError); AccountManager.instance.BuyShe(); }
// // GET: /Purchase/Details/5 public ViewResult Details(int id) { Purchase purchase = db.Purchases.Find(id); return(View(purchase)); }
public PurchaseResponse(Purchase purchase) : this(string.Empty, true, purchase) { }
public void Update(Purchase entity) { if (entity == null) { throw new ArgumentNullException("entity"); } if (string.IsNullOrEmpty(entity.BillNo)) { throw new ArgumentException("Purchase No cannot be empty!"); } if (entity.SupplierId == Guid.Empty) { throw new ArgumentException("Purchase supplier cannot be empty!"); } if (entity.EmployeeId == Guid.Empty) { throw new ArgumentException("Purchase Employee cannot be empty!"); } if (CheckDuplicateBillNo(entity.Id, entity.BillNo)) { throw new ArgumentException("Duplicate Purchase No found!"); } try { using (OpenPOSDbEntities ctx = new OpenPOSDbEntities()) { using (var scope = new TransactionScope(TransactionScopeOption.Required)) { ctx.ExecuteStoreCommand("DELETE FROM PurchaseDetails WHERE PurchaseId = {0};", entity.Id); ctx.ExecuteStoreCommand("DELETE FROM PurchasePayments WHERE PurchaseId = {0};", entity.Id); foreach (var od in entity.PurchaseDetails) { ctx.AttachTo("PurchaseDetails", od); ctx.ObjectStateManager.ChangeObjectState(od, System.Data.EntityState.Added); } foreach (var payment in entity.PurchasePayments) { ctx.AttachTo("PurchasePayments", payment); ctx.ObjectStateManager.ChangeObjectState(payment, System.Data.EntityState.Added); } ctx.AttachTo("Purchases", entity); ctx.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified); ctx.SaveChanges(); scope.Complete(); } } } catch (Exception ex) { LogService.Error("Error while updating Purchase", ex); throw new ArgumentException("Error while updating Purchase", ex); } }
public async Task UpdatePurchase(Purchase newPurchase) { await _unitOfWork.Purchases.UpdateASync(newPurchase); }
public async Task <IActionResult> AddPurchase([FromBody] Purchase model) { var result = await this._service.AddPurchase(model); return(Ok(result)); }
private void consumePurchaseSucceededEvent(Purchase purchase) { Debug.Log("consumePurchaseSucceededEvent: " + purchase); }
public EditNewInvoice(Purchase purchase) : this(new List <Purchase> { purchase }) { }
public static string ImportPurchases(VaporStoreDbContext context, string xmlString) { XmlRootAttribute root = new XmlRootAttribute("Purchases"); XmlSerializer serializer = new XmlSerializer(typeof(ImportPurchaseDto[]), root); StringBuilder sb = new StringBuilder(); using StringReader sr = new StringReader(xmlString); ImportPurchaseDto[] purchaseDtos = (ImportPurchaseDto[])serializer.Deserialize(sr); List <Purchase> purchases = new List <Purchase>(); foreach (ImportPurchaseDto purchaseDto in purchaseDtos) { if (!IsValid(purchaseDto)) { sb.AppendLine(ErrorMessage); continue; } bool isValidDate = DateTime.TryParseExact(purchaseDto.Date, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date); if (!isValidDate) { sb.AppendLine(ErrorMessage); continue; } bool isTypeValid = Enum.TryParse(typeof(PurchaseType), purchaseDto.PurchaseType, out object purchaseTypeObj); if (!isTypeValid) { sb.AppendLine(ErrorMessage); continue; } Card card = context.Cards.FirstOrDefault(c => c.Number == purchaseDto.CardNumber); if (card == null) { sb.AppendLine(ErrorMessage); continue; } Game game = context.Games.FirstOrDefault(g => g.Name == purchaseDto.Title); if (game == null) { sb.AppendLine(ErrorMessage); continue; } Purchase p = new Purchase() { Game = game, Card = card, Date = date, Type = (PurchaseType)purchaseTypeObj, ProductKey = purchaseDto.Key }; purchases.Add(p); sb.AppendLine(String.Format(SuccessfullyImportedPurchase, p.Game.Name, p.Card.User.Username)); } context.Purchases.AddRange(purchases); context.SaveChanges(); return(sb.ToString().TrimEnd()); }
// Invoice // Expense // Payable // Purchase // Stock // StockIn // Transaction public async Task <WrapperPurchaseListVM> DeletePurchaseAsync(PurchaseVM vm) { Task <List <Invoice> > invoiceToDelete = _repositoryWrapper .Invoice .FindAll() .Where(x => x.Id == vm.InvoiceId && x.FactoryId == vm.FactoryId) .ToListAsync(); Task <List <Expense> > expenseToDelete = _repositoryWrapper .Expense .FindAll() .Where(x => x.InvoiceId == vm.InvoiceId && x.FactoryId == vm.FactoryId) .ToListAsync(); Task <List <Payable> > payableToDelete = _repositoryWrapper .Payable .FindAll() .Where(x => x.InvoiceId == vm.InvoiceId && x.FactoryId == vm.FactoryId) .ToListAsync(); Task <List <Purchase> > purchaseToDelete = _repositoryWrapper .Purchase .FindAll() .Where(x => x.InvoiceId == vm.InvoiceId && x.FactoryId == vm.FactoryId) .ToListAsync(); await Task.WhenAll(invoiceToDelete, expenseToDelete, payableToDelete, purchaseToDelete); // Stock IEnumerable <Stock> stockList = await _repositoryWrapper .Stock .FindByConditionAsync( x => x.FactoryId == vm.FactoryId); //&& purchaseToDelete //.Result //.ToList() //.FirstOrDefault(d => d.ItemId == x.ItemId) != null); for (int i = 0; i < purchaseToDelete.Result.Count(); i++) { Purchase purchaseItem = purchaseToDelete.Result.ElementAt(i); Stock existingStock = stockList.ToList().Where(x => x.ItemId == purchaseItem.ItemId).FirstOrDefault(); if (existingStock == null) { // _utilService.Log("Stock Is Empty. Not Enough Stock available"); // throw new StockEmptyException(); } else { if (existingStock.Quantity < purchaseItem.Quantity) { var getDatalistVM2 = new GetDataListVM() { FactoryId = vm.FactoryId, PageNumber = 1, PageSize = 10 }; WrapperPurchaseListVM vm2 = await GetAllPurchaseAsync(getDatalistVM2); vm2.HasMessage = true; vm2.Message = "Stock hasn't enough item"; return(vm2); } else { existingStock.Quantity -= purchaseItem.Quantity; _repositoryWrapper.Stock.Update(existingStock); } } } Task <List <StockIn> > stockInToDelete = _repositoryWrapper .StockIn .FindAll() .Where(x => x.InvoiceId == vm.InvoiceId && x.FactoryId == vm.FactoryId) .ToListAsync(); Task <List <TblTransaction> > transactionToDelete = _repositoryWrapper .Transaction .FindAll() .Where(x => x.InvoiceId == vm.InvoiceId && x.FactoryId == vm.FactoryId) .ToListAsync(); _repositoryWrapper.Invoice.DeleteAll(invoiceToDelete.Result.ToList()); _repositoryWrapper.Expense.DeleteAll(expenseToDelete.Result.ToList()); _repositoryWrapper.Payable.DeleteAll(payableToDelete.Result.ToList()); _repositoryWrapper.Purchase.DeleteAll(purchaseToDelete.Result.ToList()); _repositoryWrapper.StockIn.DeleteAll(stockInToDelete.Result.ToList()); _repositoryWrapper.Transaction.DeleteAll(transactionToDelete.Result.ToList()); Task <int> Invoice = _repositoryWrapper.Invoice.SaveChangesAsync(); Task <int> Expense = _repositoryWrapper.Expense.SaveChangesAsync(); Task <int> Payable = _repositoryWrapper.Payable.SaveChangesAsync(); Task <int> Purchase = _repositoryWrapper.Purchase.SaveChangesAsync(); Task <int> StockIn = _repositoryWrapper.StockIn.SaveChangesAsync(); Task <int> TblTransaction = _repositoryWrapper.Transaction.SaveChangesAsync(); Task <int> Stock = _repositoryWrapper.Stock.SaveChangesAsync(); await Task.WhenAll(Invoice, Expense, Payable, Purchase, StockIn, TblTransaction, Stock); var getDatalistVM = new GetDataListVM() { FactoryId = vm.FactoryId, PageNumber = 1, PageSize = 10 }; return(await GetAllPurchaseAsync(getDatalistVM)); }
public bool SavePurchase(Purchase purchase) { return(purchaseRepository.SavePurchase(purchase)); }
//CRUD Functions private bool Add(Purchase purchase) { return(_purchaseManager.Add(purchase)); }
//Buttons private void addButton_Click(object sender, EventArgs e) { try { _purchase = new Purchase(); _purchase.ProductId = _productId; _purchase.Date = Convert.ToDateTime(supplierDate.Text); _purchase.InvoiceNo = invoiceNoTextBox.Text; _purchase.Supplier = supplierComboBox.Text; _purchase.Category = categoryComboBox.Text; _purchase.Products = productsComboBox.Text; _purchase.ProductCode = productCodeTextBox.Text; _purchase.ManufactureDate = DateTime.Parse(manufacturedDatePicker.Text); _purchase.ExpireDate = DateTime.Parse(expireDatePicker.Text); _purchase.Quantity = int.Parse(quantityTextBox.Text); _purchase.UnitPrice = double.Parse(unitPriceTextBox.Text); _purchase.TotalPrice = double.Parse(totalPriceTextBox.Text); _purchase.PreviousUnitPrice = double.Parse(previousUnitPriceTextBox.Text); _purchase.PreviousMRP = double.Parse(previousMrpTextBox.Text); _purchase.MRP = double.Parse(mrpTextBox.Text); _purchase.Remarks = remarksTextBox.Text; if (addButton.Text.Equals("Add")) { if (!IsValid(_purchase)) { return; } if (!IsUnique(_purchase)) { return; } if (samePurchase(_purchase.ProductCode, _purchaseList)) { return; } _purchaseList.Add(_purchase); ResetInputs(); ResetErrorLabels(); DisplayRecords(_purchaseList, _itemList); } else if (addButton.Text.Equals("Modify")) { int indexNo = GetItemIndexNo(_purchaseList); if (indexNo != -1) { _purchaseList.RemoveAt(indexNo); _purchaseList.Insert(indexNo, _purchase); ResetInputs(); ResetErrorLabels(); DisplayRecords(_purchaseList, _itemList); } } }catch (Exception error) { ExceptionMessage(error); } }
public DataTable Search(Purchase purchase) { //Connection string connectionString = @"Server=DESKTOP-CR4IGJV; Database=SMS_RAMPAGE; Integrated Security=True"; SqlConnection sqlConnection = new SqlConnection(connectionString); //Command string commandString = @"SELECT Product.Code,Product.Name,Category.Name As Category, SUM(Purchase_Details.Quantity)-(SELECT SUM(Quantity) FROM Sales_Details WHERE Purchase_Details.Product_Id=Sales_Details.Product_Id GROUP BY Sales_Details.Product_Id) AS Available_Qty, (SUM(Purchase_Details.Quantity)-(SELECT SUM(Quantity) FROM Sales_Details WHERE Purchase_Details.Product_Id=Sales_Details.Product_Id GROUP BY Sales_Details.Product_Id))* SUM(Purchase_Details.Unit_Price)/COUNT(*) AS CP, (SUM(Purchase_Details.Quantity)-(SELECT SUM(Quantity) FROM Sales_Details WHERE Purchase_Details.Product_Id=Sales_Details.Product_Id GROUP BY Sales_Details.Product_Id))* SUM(Purchase_Details.MRP)/COUNT(*) AS MRP, (SUM(Purchase_Details.Quantity)-(SELECT SUM(Quantity) FROM Sales_Details WHERE Purchase_Details.Product_Id=Sales_Details.Product_Id GROUP BY Sales_Details.Product_Id))* SUM(Purchase_Details.MRP)/COUNT(*)-(SUM(Purchase_Details.Quantity)-(SELECT SUM(Quantity) FROM Sales_Details WHERE Purchase_Details.Product_Id=Sales_Details.Product_Id GROUP BY Sales_Details.Product_Id))* SUM(Purchase_Details.Unit_Price)/COUNT(*) AS Profit FROM Purchase_Details LEFT JOIN Product ON Purchase_Details.Product_Id=Product.Id LEFT JOIN Category ON Product.Category_Id=Category.Id LEFT JOIN Purchase ON Purchase_Details.Purchase_Id=Purchase.Id WHERE Purchase.Date1 >='" + purchase.Date1 + "' and Purchase.Date1<='" + purchase.Date2 + "' GROUP BY Purchase_Details.Product_Id,Product.Name,Product.Code, Category.Name"; SqlCommand sqlCommand = new SqlCommand(commandString, sqlConnection); //Open sqlConnection.Open(); //Show //With DataAdapter SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); DataTable dataTable = new DataTable(); sqlDataAdapter.Fill(dataTable); //With DataAdapter //SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); //List<Customer> customers = new List<Customer>(); //while (sqlDataReader.Read()) //{ // Customer customer = new Customer(); // //District district = new District(); // customer.Id = Convert.ToInt32(sqlDataReader["Id"]); // customer.Code = sqlDataReader["Code"].ToString(); // customer.Name = sqlDataReader["Name"].ToString(); // customer.Address = sqlDataReader["Address"].ToString(); // customer.Contact = sqlDataReader["Contact"].ToString(); // customer.District_Id =Convert.ToInt32(sqlDataReader["District_Id"]); // // district.Name = sqlDataReader["District_Name"].ToString(); // customers.Add(customer); //} //if (sqlDataReader.NextResult()) //{ // while (sqlDataReader.Read()) // { // District district = new District(); // district.Name = sqlDataReader["District_Name"].ToString(); // //customers.Add(district); // } //} //if (dataTable.Rows.Count > 0) //{ // //showDataGridView.DataSource = dataTable; //} //else //{ // //MessageBox.Show("No Data Found"); //} //Close sqlConnection.Close(); //return dataTable; return(dataTable); }
private DbInsertStatement GetQuery_InsertQuery(Purchase _obj) { Dictionary <string, DbFieldEntry> fields = GetFields(_obj); return(DbMgr.CreateInsertClause("Purchases", fields)); }
public UpgradeMembershipCommand(Purchase purchase, Product membership) { Membership = membership; Purchase = purchase; }
private DbUpdateStatement GetQuery_UpdateQuery(Purchase _obj) { return(DbMgr.CreateUpdateClause("Purchases", GetFields(_obj), "PurchaseID", _obj.PurchaseID)); }
public async Task DeletePurchase(Purchase purchase) { _unitOfWork.Purchases.DeleteAsync(purchase); await _unitOfWork.CommitAsync(); }
private int AddColPurchase(Cell cell, ref Purchase sr, int c) { Logs.LogMe("cell(" + cell.ColumnIndex + ")=" + cell.Text); switch (cell.ColumnIndex) { case 0: sr.GRNNo = cell.Text; c++; break; case 1: sr.GRNDate = DataConvertor.DateFromExcelFormat(cell.Text); c++; break; case 2: sr.InvoiceNo = cell.Text; c++; break; case 3: sr.InvoiceDate = DataConvertor.DateFromExcelFormat(cell.Text); c++; break; case 4: sr.SupplierName = cell.Text; c++; break; case 5: sr.Barcode = cell.Text; c++; break; case 6: sr.ProductName = cell.Text; c++; break; case 7: sr.StyleCode = cell.Text; c++; break; case 8: sr.ItemDesc = cell.Text; c++; break; case 9: sr.Quantity = cell.Amount; c++; break; case 10: sr.MRP = cell.Amount; c++; break; case 11: sr.MRPValue = cell.Amount; c++; break; case 12: sr.Cost = cell.Amount; c++; break; case 13: sr.CostValue = cell.Amount; c++; break; case 14: sr.TaxAmt = cell.Amount; c++; break; } return(c); }
public async Task <ActionResult> Index(CheckoutModel model) { //Check if the model-state is valid -- this will catch anytime someone hacks your client-side validation if (ModelState.IsValid) { if (model.CustomerId == null) { BraintreeService service = new BraintreeService(this._braintreeGateway); model.CustomerId = await service.GetCustomerId(model.Email, model.Phone, model.FirstName, model.LastName); } if ((model.CardToken == "NewCard") || (model.CardToken == null)) { Braintree.CreditCardRequest card = new Braintree.CreditCardRequest(); card.Number = model.CreditCardNumber; card.CVV = model.CreditCardVerificationValue; card.ExpirationMonth = model.CreditCardExpirationMonth.ToString().PadLeft(2, '0'); card.ExpirationYear = model.CreditCardExpirationYear.ToString(); card.CardholderName = model.BillingFirstName + " " + model.BillingLastName; card.CustomerId = model.CustomerId; var cardResult = await _braintreeGateway.CreditCard.CreateAsync(card); model.CardToken = cardResult.Target.Token; } if ((model.BillingAddressId == "NewAddress") || (model.BillingAddressId == null)) { Braintree.AddressRequest address = new Braintree.AddressRequest(); address.StreetAddress = model.BillingAddressLine1 + " " + model.BillingAddressLine2; address.CountryName = model.BillingCountry; address.Locality = model.BillingCity; address.PostalCode = model.BillingPostalCode; address.Region = model.BillingState; var addressResult = await _braintreeGateway.Address.CreateAsync(model.CustomerId, address); model.BillingAddressId = addressResult.Target.Id; } if ((model.ShippingAddressId == "NewAddress") || (model.ShippingAddressId == null)) { if ((model.ShippingAddressLine1 == model.BillingAddressLine1) && (model.ShippingAddressLine2 == model.BillingAddressLine2) && (model.ShippingCity == model.BillingCity) && (model.ShippingPostalCode == model.BillingPostalCode) && (model.ShippingState == model.BillingState) && (model.ShippingCountry == model.BillingCountry)) { model.ShippingAddressId = model.BillingAddressId; } else { Braintree.AddressRequest address = new Braintree.AddressRequest(); address.StreetAddress = model.ShippingAddressLine1 + " " + model.ShippingAddressLine2; address.CountryName = model.ShippingCountry; address.Locality = model.ShippingCity; address.PostalCode = model.ShippingPostalCode; address.Region = model.ShippingState; var addressResult = await _braintreeGateway.Address.CreateAsync(model.CustomerId, address); model.ShippingAddressId = addressResult.Target.Id; } } Shipment s = new Shipment { AddressLine1 = model.ShippingAddressLine1, AddressLine2 = model.ShippingAddressLine2, City = model.ShippingCity, State = model.ShippingState, PostalCode = model.ShippingPostalCode, Country = model.ShippingCountry, Modified = DateTime.UtcNow, Created = DateTime.UtcNow }; Purchase p = new Purchase { SubmittedDate = DateTime.UtcNow, AspNetUserID = User.Identity.IsAuthenticated ? db.AspNetUsers.First(x => x.UserName == User.Identity.Name).Id : null, Created = DateTime.UtcNow, Modified = DateTime.UtcNow, OrderIdentifier = Guid.NewGuid().ToString().Substring(0, 8), PurchaseProducts = this.GetBasket(db).BasketProducts.Select(x => new Models.PurchaseProduct { ProductID = x.ProductID, Quantity = x.Quantity, Created = DateTime.UtcNow, Modified = DateTime.UtcNow, ProductName = x.Product.Name, ProductPrice = x.Product.Price, Shipment = s, }).ToArray() }; db.Purchases.Add(p); db.Baskets.Remove(this.GetBasket(db)); db.SaveChanges(); Braintree.TransactionRequest transaction = new Braintree.TransactionRequest(); transaction.Amount = this.GetBasket(db).BasketProducts.Sum(x => x.Quantity * (x.Product.Price ?? 0)); transaction.CustomerId = model.CustomerId; transaction.PaymentMethodToken = model.CardToken; transaction.OrderId = p.ID.ToString(); transaction.PurchaseOrderNumber = p.OrderIdentifier; var transactionResult = await _braintreeGateway.Transaction.SaleAsync(transaction); await _emailService.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage { Subject = string.Format("Your Coding Cookware Order {0}", p.OrderIdentifier), Destination = model.Email, Body = CreateReceiptEmail(p) }); if (!string.IsNullOrEmpty(model.Phone)) { await _smsService.SendAsync(new Microsoft.AspNet.Identity.IdentityMessage { Subject = "", Destination = model.Phone, Body = "You placed order " + p.OrderIdentifier }); } return(RedirectToAction("Index", "Receipt", new { id = p.OrderIdentifier })); } ; return(View()); }
public async Task InsertPurchase(Purchase purchase) { await _context.Purchase.AddAsync(purchase); }
public PurchaseResponse(string message, bool success, Purchase purchase) : base(message, success) { Purchase = purchase; }
private void purchaseSucceededEvent(Purchase purchase) { Debug.Log("purchaseSucceededEvent: " + purchase); }
public abstract void ProcessRequest(Purchase purchase);
public NewErrorModel ChangeBom(List <DrawingChange> DrawingChangeList) { try { DDContext context = new DDContext(); foreach (var item in DrawingChangeList) { if (item.ChangeType == "1") //新增 { Purchase purchase = new Purchase() { TaskId = item.TaskId, AllWeight = item.AllWeight, BomId = item.BomId, Brand = item.Brand, ChangeType = item.ChangeType, CodeNo = item.CodeNo, Count = item.Count, DrawingNo = item.DrawingNo, Mark = item.Mark, MaterialScience = item.MaterialScience, Name = item.Name, NeedTime = item.NeedTime, SingleWeight = item.SingleWeight, Sorts = item.Sorts, Unit = item.Unit }; context.Purchase.Add(purchase); context.SaveChanges(); } if (item.ChangeType == "2") //删除 { Purchase purchase = context.Purchase.Find(Int32.Parse(item.OldId)); purchase.ChangeType = item.ChangeType; context.Entry <Purchase>(purchase).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } } //Tasks tasks = context.Tasks.Where(t => t.TaskId.ToString() // == drawingChangeTable.fileChange.TaskId.ToString() && t.NodeId == 0).FirstOrDefault(); //tasks.MediaId = drawingChangeTable.fileChange.MediaId; //tasks.MediaIdPDF = drawingChangeTable.fileChange.MediaIdPDF; //tasks.FilePDFUrl = drawingChangeTable.fileChange.FilePDFUrl; //tasks.OldFilePDFUrl = drawingChangeTable.fileChange.OldFilePDFUrl; //tasks.FileUrl = drawingChangeTable.fileChange.FileUrl; //tasks.OldFileUrl = drawingChangeTable.fileChange.OldFileUrl; //context.Entry<Tasks>(tasks).State = System.Data.Entity.EntityState.Modified; //context.SaveChanges(); return(new NewErrorModel() { data = "", error = new Error(0, "变更成功!", "") { }, }); } catch (Exception ex) { return(new NewErrorModel() { error = new Error(1, ex.Message, "") { }, }); } }
// // GET: /Purchase/Delete/5 public ActionResult Delete(int id) { Purchase purchase = db.Purchases.Find(id); return(View(purchase)); }
public Purchase Update(Purchase purchase) { _purchaseRepository.Update(purchase); return(purchase); }
public IHttpActionResult SavePurchase(Purchase purchase) { return(Ok(_service.Add(purchase))); }
public Purchase Add(Purchase purchase) { _purchaseRepository.Add(purchase); return(purchase); }
// fired after a successful consumption (see PurchaseVerified()). // Method that fires the purchase succeeded action private void ConsumeSucceeded(Purchase prod) { inventory.ErasePurchase(prod.Sku); purchaseSucceededEvent(GetIAPIdentifier(prod.Sku)); }
public static string ImportPurchases(VaporStoreDbContext context, string xmlString) { XDocument document = XDocument.Parse(xmlString); string dateFormat = @"dd/MM/yyyy HH:mm"; var elements = document.Root.Elements().ToList(); StringBuilder builder = new StringBuilder(); foreach (var element in elements) { var currentPurchaseDto = new PurchaseDto() { Title = element.Attribute("title").Value, Type = element.Element("Type").Value, ProductKey = element.Element("Key").Value, Date = DateTime.ParseExact(element.Element("Date").Value, dateFormat, CultureInfo.InvariantCulture), Card = element.Element("Card").Value }; PurchaseType currentPurchaseType; bool isTypeParseSuccessfull = Enum.TryParse <PurchaseType>(currentPurchaseDto.Type, out currentPurchaseType); if (IsValid(currentPurchaseDto) == false || isTypeParseSuccessfull == false) { continue; } Purchase currentPurchase = new Purchase() { Date = currentPurchaseDto.Date, Type = currentPurchaseType }; var currentGame = GetObjectFromSet <Game>(x => x.Name == currentPurchaseDto.Title, context); if (currentGame == null) { continue; } var currentCard = GetObjectFromSet <Card>(x => x.Number == currentPurchaseDto.Card, context); if (currentCard == null) { continue; } currentPurchase.Game = currentGame; currentPurchase.Card = currentCard; currentPurchase.ProductKey = currentPurchaseDto.ProductKey; string currentUsernameOfBuyer = GetObjectFromSet <User>(x => x.Cards.Any(z => z.Number == currentCard.Number), context).Username; context.Purchases.Add(currentPurchase); builder.AppendLine($"Imported {currentGame.Name} for {currentUsernameOfBuyer}"); } context.SaveChanges(); return(builder.ToString().TrimEnd()); }