public void TestConstructor() { Trade trade = new Trade(sunshine, 100.0f, 100); TransactionItem t1 = new TransactionItem(trade); TransactionItem t2 = new TransactionItem(trade, 50); TransactionItem t3 = new TransactionItem(trade, 150); Assert.AreEqual(100, t1.Quantity); Assert.AreEqual(50, t2.Quantity); Assert.AreEqual(100, t3.Quantity); }
public void TestFixtureSetUp() { sunshine = new ItemType(1, "Sunshine", 1.5f); p1 = new Trade(sunshine, 1.0f, 100); p2 = new Trade(sunshine, 10.0f, 10); s1 = new Trade(sunshine, 5.0f, 100); s2 = new Trade(sunshine, 50.0f, 100); pt1 = new TransactionItem(p1); pt2 = new TransactionItem(p2); st1 = new TransactionItem(s1); st2 = new TransactionItem(s2); }
static Transactions() { OpenFile(); TransactionItem item = new TransactionItem() { TransactionId = CurrentState.LastTransactionId, DateTime = DateTime.UtcNow, Type = TransactionItemType.Creation, Source = Net.Link.Source, Linker = Net.Link.Linker, Target = Net.Link.Target, }; //LogAccessor. += Marshal.SizeOf(typeof(TransactionItem)); EnsureFileSize(); LogAccessor.Write<TransactionItem>(BasicTransactionsOffset, ref item); LogAccessor.Read<TransactionItem>(BasicTransactionsOffset, out item); CloseFile(); }
public double AddPurchaseTransaction(int productId) { _state = eTransactionState.Purchase; ProductItem product = _db.GetProductItem(productId); TransactionItem transactionItem = new TransactionItem(); transactionItem.ProductId = productId; transactionItem.SalePrice = product.Price; _transactionItems.Add(transactionItem); VendingOperation operation = new VendingOperation(); operation.OperationType = VendingOperation.eOperationType.PurchaseItem; operation.Price = product.Price; operation.RunningTotal = _runningTotal; operation.ProductName = product.Name; _log.LogOperation(operation); _runningTotal -= product.Price; return(_runningTotal); }
public bool TryGetMonthReports(FileData data, out TransactionReport report) { report = new TransactionReport() { Transactions = new List <Transaction>() }; string header = data.Lines.FirstOrDefault(); bool canParse = CheckIfValidFile(header); if (!canParse) { return(false); } for (int i = 1; i < data.Lines.Count; i++) { string line = data.Lines[i]; TransactionItem item = GetFromLine(line); if (item.IsNullObj()) { continue; } Transaction transaction = CreateFromTransactionItem(item); if (transaction.IsNullObj()) { continue; } report.Transactions.Add(transaction); } return(true); }
public Comparisons(List <string> comparators) { InitializeComponent(); DataTable dt = new DataTable(); dt.Columns.Add("Date"); foreach (TransactionItem.TransactionTypes types in Enum.GetValues(typeof(TransactionItem.TransactionTypes))) { dt.Columns.Add(types.ToString()); } dt.Columns.Add("Total"); var items = TransactionItem.GetCollection().FindAll().GroupBy(t => t.TransDate.ToString("MMM yyyy")).ToDictionary(k => k.Key, e => e.ToList()); foreach (string compare in comparators) { DataRow row = dt.NewRow(); row["Date"] = compare; decimal total = 0; foreach (TransactionItem.TransactionTypes types in Enum.GetValues(typeof(TransactionItem.TransactionTypes))) { decimal subtotal = items .Where(i => i.Key.Contains(compare)) .SelectMany(i => i.Value) .Where(i => i.TransType == types) .Sum(i => i.Amount); total += subtotal; row[types.ToString()] = subtotal; } row["Total"] = total; dt.Rows.Add(row); } dgCompare.DataSource = dt; }
public static void SignSignature(this TransactionItem transactionItem, int[] addressPrivateKey, ICurl curl) { var value = transactionItem.Value; if (value > 0) { return; } //throw new IotaException($"Cannot sign transaction with value greater than 0. Current value '{value}'"); int index = value < 0 ? 0 : 1; var normalizedBundleHash = TransactionExtensions.NormalizedBundle(transactionItem.Bundle); // First 6561 trits for the firstFragment int[] firstFragment = ArrayUtils.SubArray2(addressPrivateKey, 6561 * index, 6561); // First bundle fragment uses 27 trytes int[] firstBundleFragment = ArrayUtils.SubArray2(normalizedBundleHash, 27 * index, 27); // Calculate the new signatureFragment with the first bundle fragment int[] firstSignedFragment = new Signing(curl).SignatureFragment(firstBundleFragment, firstFragment); // Convert signature to trytes and assign the new signatureFragment transactionItem.SignatureFragment = Converter.ToTrytes(firstSignedFragment); }
public ChangeBranch(TransactionItem transactionItem) { myChanges = PartitionChange.GetPartitionChanges(transactionItem); }
private void ProcessOrderEvent(Order order, bool add) { try { //settings per store var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore; var googleAnalyticsSettings = _settingService.LoadSetting <GoogleAnalyticsSettings>(store.Id); var request = new GoogleRequest { AccountCode = googleAnalyticsSettings.GoogleId, Culture = "en-US", HostName = new Uri(_webHelper.GetThisPageUrl(false)).Host, PageTitle = add ? "AddTransaction" : "CancelTransaction" }; var orderId = order.CustomOrderNumber; var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax; var orderTax = order.OrderTax; var orderTotal = order.OrderTotal; if (!add) { orderShipping = -orderShipping; orderTax = -orderTax; orderTotal = -orderTotal; } var trans = new Transaction(FixIllegalJavaScriptChars(orderId), order.BillingAddress == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.City), order.BillingAddress == null || order.BillingAddress.Country == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.Country.Name), order.BillingAddress == null || order.BillingAddress.StateProvince == null ? "" : FixIllegalJavaScriptChars(order.BillingAddress.StateProvince.Name), store.Name, orderShipping, orderTax, orderTotal); foreach (var item in order.OrderItems) { //get category var category = _categoryService.GetProductCategoriesByProductId(item.ProductId).FirstOrDefault()?.Category?.Name; var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax; var qty = item.Quantity; if (!add) { qty = -qty; } var sku = _productService.FormatSku(item.Product, item.AttributesXml); if (String.IsNullOrEmpty(sku)) { sku = item.Product.Id.ToString(); } var product = new TransactionItem(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(sku), FixIllegalJavaScriptChars(item.Product.Name), unitPrice, qty, FixIllegalJavaScriptChars(category)); trans.Items.Add(product); } request.SendRequest(trans, _httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient)); } catch (Exception ex) { _logger.InsertLog(LogLevel.Error, "Google Analytics. Error canceling transaction from server side", ex.ToString()); } }
private void btnCreate_Click(object sender, RoutedEventArgs e) { var push = new Transaction(DateTime.Now); myContext.Transaction.Add(push); var result = myContext.SaveChanges(); if (result > 0) { var tsc = myContext.Transaction.OrderByDescending(t => t.id).First(); foreach (var s in TList) { var isi = new TransactionItem(s.quantity, tsc, s.Item); myContext.TcItem.Add(isi); myContext.SaveChanges(); } //var it= Imported_Transaction.Items; //for (int i = 0; i <= Imported_Transaction.Items.Count; ++i) //{ // string nama = (Imported_Transaction.SelectedCells[1].Column.GetCellContent(it[i]) as TextBlock).Text; // var itm = myContext.Item.Where(j => j.Name==nama).SingleOrDefault(); // int qty = Convert.ToInt32((Imported_Transaction.Columns[2].GetCellContent(it[i]) as TextBlock).Text); // var push_ti = new TransactionItem(qty, tsc, itm); // myContext.TcItem.Add(push_ti); // myContext.SaveChanges(); //} //Bisa! //Create a new PDF document. PdfDocument doc = new PdfDocument(); //Add a page. PdfPage page = doc.Pages.Add(); PdfGraphics graphics = page.Graphics; //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); string judul = "---- Barang----";// +Qty; string isian = "Total Harga : " + TxtTotal.Text + "\nUang yang dibayarkan : " + TxtPay.Text + "\nKembalian : " + TxtReturn.Text; PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); graphics.DrawString(judul, font, PdfBrushes.Black, new PointF(0, 0)); //Header : //Create a DataTable. DataTable dataTable = new DataTable(); //Add columns to the DataTable dataTable.Columns.Add("Barang"); dataTable.Columns.Add("QTY"); dataTable.Columns.Add("Harga"); //Add rows to the DataTable. foreach (var p in TList) { int harga = p.Item.Price * p.quantity; dataTable.Rows.Add(new object[] { p.Item.Name, p.quantity, harga }); } //Assign data source. pdfGrid.DataSource = dataTable; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new PointF(0, 30)); graphics.DrawString(isian, font, PdfBrushes.Black, new PointF(0, 150)); //Save the document. doc.Save("Struk.pdf"); System.Diagnostics.Process.Start("Struk.pdf"); //close the document doc.Close(true); //using (PdfDocument document = new PdfDocument()) //{ // //Add a page to the document // PdfPage page = document.Pages.Add(); // //Create PDF graphics for a page // PdfGraphics graphics = page.Graphics; // //Set the standard font // PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); // //Draw the text // //string Qty ;//= Imported_Transaction.SelectedValue(); // string judul = "---- Barang----";// +Qty; // string isi = "Total Harga : " + TxtTotal.Text + "\nUang yang dibayarkan : " + TxtPay.Text + "\nKembalian : " + TxtReturn.Text; // graphics.DrawString(judul, font, PdfBrushes.Black, new PointF(0, 0)); // graphics.DrawString(isi, font, PdfBrushes.Black, new PointF(0, 15)); // //Save the document // document.Save("Struk.pdf"); // #region View the Workbook // //Message box confirmation to view the created document. // string pesan = "Total Kembalian = " + TxtReturn.Text + ", Ingin Mencetak Struk?"; // if (MessageBox.Show(pesan, "Struk PDF has been created", // MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) // { // try // { // //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer] // System.Diagnostics.Process.Start("Struk.pdf"); // //Exit // //Close(); // } // catch (Win32Exception ex) // { // Console.WriteLine(ex.ToString()); // } // } // else // Close(); // #endregion //} } }
/// <summary> /// Called when a property of the model associated with this view model has changed. /// ChannelControlViewModel forwards this change to the associated model so that the model can respond to property changes /// that require interactions with the VeriStand gateway /// </summary> /// <param name="modelElement">The model that changed.</param> /// <param name="propertyName">The name of the property that changed.</param> /// <param name="transactionItem">The transaction item associated with the change.</param> public override void ModelPropertyChanged(Element modelElement, string propertyName, TransactionItem transactionItem) { base.ModelPropertyChanged(modelElement, propertyName, transactionItem); ((PulseWidthModulationControlModel)Model).PropertyChanged(modelElement, propertyName, transactionItem); }
public override void ModelPropertyChanged(Element modelElement, string propertyName, TransactionItem transactionItem) { base.ModelPropertyChanged(modelElement, propertyName, transactionItem); if (propertyName == "IsActive") { NotifyPropertyChanged("IsActive"); } }
//returns a list of TransactionIems from approved Request Orders of a given dept public List <TransactionItem> GenerateDeptRetrievalList(string deptID, bool toSave) { //requisitionOrders are approved List <DocumentItem> docItemsArray = new List <DocumentItem>(); //retrieve all RO with status approved List <RequisitionOrder> ROList = new List <RequisitionOrder>(); var approvedRO = (List <RequisitionOrder>)unitOfWork.RequisitionOrderRepository.Get(filter: x => x.Status == Models.Status.Approved, includeProperties: "DocumentItems.Item,CreatedByStaff.Department"); Debug.WriteLine("Number of approved ROs: " + approvedRO.Count); //filter by department foreach (RequisitionOrder RO in approvedRO) { //Debug.WriteLine("RO ID: " + RO.ID); //Debug.WriteLine("RO is created by: " + RO.CreatedByStaff.Name + " from " + RO.CreatedByStaff.Department.ID); string deptRO = RO.CreatedByStaff.Department.ID; Debug.WriteLine("RO is from dept: " + deptRO); if (deptRO.Equals(deptID)) { if (toSave == true) { //Debug.WriteLine("Setting RO status to Completed..."); UpdateRequestionOrderStatus(RO, 4); //Set Status to "Completed" } ROList.Add(RO); } Debug.WriteLine("Number of elements in ROList: " + ROList.Count); } //get all ROs DI into a combined list List <DocumentItem> combinedDocList = new List <DocumentItem>(); for (int i = 0; i < ROList.Count; i++) { var docList = ROList[i].DocumentItems; foreach (DocumentItem doc in docList) { combinedDocList.Add(doc); } } Debug.WriteLine("Combined Doc List size: " + combinedDocList.Count); List <TransactionItem> tempTransItems = new List <TransactionItem>(); List <TransactionItem> transItemList = new List <TransactionItem>(); if (transItemList.Count == 0 && combinedDocList.Count > 0) { TransactionItem item = new TransactionItem(0, 0, null, combinedDocList[0].Item); tempTransItems.Add(item); //Debug.WriteLine("first temp trans item"); } //group all DI by item.ID, construct TI with sum of qty in DIs //add TI into a list foreach (DocumentItem doc in combinedDocList) { bool isExist = false; TransactionItem temp; int index = 0; for (int i = 0; i < transItemList.Count; i++) { temp = transItemList[i]; if (temp.Item.ID.Equals(doc.Item.ID)) { isExist = true; index = i; break; } } if (isExist) { transItemList[index].HandOverQty += doc.Qty; transItemList[index].TakeOverQty += doc.Qty; } else { TransactionItem item = new TransactionItem(doc.Qty, doc.Qty, "Retrieval", doc.Item); transItemList.Add(item); } } /* foreach (TransactionItem item in transItemList) * { * Debug.WriteLine("TransItem List: " + item.Item.Description + " " + item.HandOverQty); * }*/ return(transItemList); }
private async Task ProcessOrderEventAsync(Order order, bool add) { try { //settings per store var store = await _storeService.GetStoreByIdAsync(order.StoreId) ?? await _storeContext.GetCurrentStoreAsync(); var googleAnalyticsSettings = await _settingService.LoadSettingAsync <GoogleAnalyticsSettings>(store.Id); var request = new GoogleRequest { AccountCode = googleAnalyticsSettings.GoogleId, Culture = "en-US", HostName = new Uri(_webHelper.GetThisPageUrl(false)).Host, PageTitle = add ? "AddTransaction" : "CancelTransaction" }; var orderId = order.CustomOrderNumber; var orderShipping = googleAnalyticsSettings.IncludingTax ? order.OrderShippingInclTax : order.OrderShippingExclTax; var orderTax = order.OrderTax; var orderTotal = order.OrderTotal; if (!add) { orderShipping = -orderShipping; orderTax = -orderTax; orderTotal = -orderTotal; } var billingAddress = await _addressService.GetAddressByIdAsync(order.BillingAddressId); var trans = new Transaction(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(billingAddress.City), await _countryService.GetCountryByAddressAsync(billingAddress) is Country country ? FixIllegalJavaScriptChars(country.Name) : string.Empty, await _stateProvinceService.GetStateProvinceByAddressAsync(billingAddress) is StateProvince stateProvince ? FixIllegalJavaScriptChars(stateProvince.Name) : string.Empty, store.Name, orderShipping, orderTax, orderTotal); foreach (var item in await _orderService.GetOrderItemsAsync(order.Id)) { var product = await _productService.GetProductByIdAsync(item.ProductId); //get category var category = (await _categoryService.GetCategoryByIdAsync((await _categoryService.GetProductCategoriesByProductIdAsync(product.Id)).FirstOrDefault()?.CategoryId ?? 0))?.Name; var unitPrice = googleAnalyticsSettings.IncludingTax ? item.UnitPriceInclTax : item.UnitPriceExclTax; var qty = item.Quantity; if (!add) { qty = -qty; } var sku = await _productService.FormatSkuAsync(product, item.AttributesXml); if (string.IsNullOrEmpty(sku)) { sku = product.Id.ToString(); } var productItem = new TransactionItem(FixIllegalJavaScriptChars(orderId), FixIllegalJavaScriptChars(sku), FixIllegalJavaScriptChars(product.Name), unitPrice, qty, FixIllegalJavaScriptChars(category)); trans.Items.Add(productItem); } await request.SendRequest(trans, _httpClientFactory.CreateClient(NopHttpDefaults.DefaultHttpClient)); } catch (Exception ex) { await _logger.InsertLogAsync(LogLevel.Error, "Google Analytics. Error canceling transaction from server side", ex.ToString()); } }
public Task <int> Transfer(TransactionItem from, TransactionItem to, TransactionOptions options) { Task <int> r = Task.FromResult(0); using (MySqlConnection conn = new MySqlConnection(connStr)) { conn.Open(); MySqlTransaction tran = conn.BeginTransaction(); string fromSql = @" INSERT INTO TransactionItem (`Id`, `UserId`, `AccountNo`, `BankNo`, `Amount`, `Status`, `LastUpdateTime`, `Comment`) VALUES (@Id, @UserId, @AccountNo, @BankNo, @Amount, @Status, @LastUpdateTime, @Comment); UPDATE UserAccount SET Balance =Balance-@Amount, LastUpdateTime= NOW() WHERE UserId=@UserId and Balance-@Amount>0 limit 1; "; try { r = conn.ExecuteAsync(fromSql, new { from.Id, from.UserId, from.AccountNo, from.BankNo, from.Amount, from.Status, from.LastUpdateTime, from.Comment }, tran); tran.Commit(); } catch { tran.Rollback(); } finally { conn.Close(); conn.Dispose(); } } return(r); }
public void addTransactionItem(string options) { if (!_trackerStarted) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Tracker not started")); return; } string[] args = JsonHelper.Deserialize<string[]>(options); if (args.Length == 0 || args[0] == null || args[0].Length == 0) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Expected non-empty ID.")); return; } TransactionItem transactionItem = new TransactionItem(); // Default values double price = 0; long quantity = 0; if (args.Length > 0) transactionItem.TransactionId = args[0]; if (args.Length > 1) transactionItem.Name = args[1]; if (args.Length > 2) transactionItem.SKU = args[2]; if (args.Length > 3) transactionItem.Category = args[3]; if (args.Length > 4) { double.TryParse(args[4], out price); transactionItem.PriceInMicros = (long)(price * 1000000); } if (args.Length > 5) { long.TryParse(args[5], out quantity); transactionItem.Quantity = quantity; } if (args.Length > 6) transactionItem.CurrencyCode = args[6]; addCustomDimensionsToTracker(_tracker); _tracker.SendTransactionItem(transactionItem); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "Add Transaction Item: " + transactionItem.TransactionId)); }
/// <summary> /// /// </summary> /// <param name="vendor"></param> /// <param name="postedData"></param> public HttpResponseMessage PostTransactionByIpn([FromUri]string id, [FromBody]FormDataCollection postedData) { var vendorId = Guid.Parse(id); var txn = new Transaction(); var d = postedData.ReadAsNameValueCollection(); //To calculate 'handshake', run 'md5 -s [password]', then 'md5 -s [email protected][Last MD5 result]' string handshakeParameter = d.Pluck("handshake",null); if (handshakeParameter == null) throw new Exception("Missing parameter 'handshake'."); using (var dataContext = dataContextFactory.Create()) { var vendor = dataContext.Vendors.Where(v => v.ObjectId == vendorId) .Include(v => v.VendorCredentials) .FirstOrDefault(); if (vendor == null) throw new Exception("Could not find vendor with id: " + vendorId); string[] vendorCredentials = vendor.VendorCredentials.Select( c => Encoding.UTF8.GetString(SymmetricEncryption.DecryptForDatabase(c.CredentialValue)).ToLower()).ToArray(); if (!vendorCredentials.Contains(handshakeParameter.ToLower())) throw new Exception("Invalid handshake provided"); } string txn_id = d.Pluck("txn_id"); //TODO: We must ignore duplicate POSTs with the same txn_id - all POSTs will contain the same information if (!"Completed".Equals(d.Pluck("payment_status"), StringComparison.OrdinalIgnoreCase)) throw new Exception("Only completed transactions should be sent to this URL"); //var txn = new Transaction(); txn.VendorId = vendorId; txn.ExternalTransactionId = txn_id; txn.PaymentDate = ConvertPayPalDateTime(d.Pluck("payment_date")); txn.PayerEmail = d.Pluck("payer_email"); txn.PassThroughData = d.Pluck("custom"); txn.Currency = d.Pluck("mc_currency"); txn.InvoiceId = d.Pluck("invoice"); txn.Gross = d.Pluck<double>("mc_gross"); txn.TransactionFee = d.Pluck<double>("mc_fee"); txn.Tax = d.Pluck<double>("tax"); txn.TransactionType = d.Pluck("transaction_type"); if (d["payer_name"] == null) d["payer_name"] = d["first_name"] + " " + d["last_name"]; txn.Billing = ParseFrom(d,"payer_"); txn.Shipping = ParseFrom(d,"address_"); var itemCount = d.Pluck<int>("num_cart_items",1); txn.Items = new List<TransactionItem>(); for (var i = 1; i <= itemCount; i++) { string suffix = i.ToString(); var item = new TransactionItem(); item.Gross = d.Pluck<double>("mc_gross_" + i.ToString()).Value; item.ItemName = d.Pluck("item_name" + i.ToString()); item.SkuString = d.Pluck("item_number" + i.ToString()); item.Options = new List<KeyValuePair<string, string>>(); for (var j = 1; j < 4; j++) { string opt_key = d.Pluck("option_name" + j.ToString() + "_" + i.ToString()); string opt_val = d.Pluck("option_selection" + j.ToString() + "_" + i.ToString()); if (string.IsNullOrEmpty(opt_val)) continue; item.Options.Add(new KeyValuePair<string, string>(opt_key, opt_val)); } var qty = d.Pluck<int>("quantity" + i.ToString(),1).Value; for(var j = 0; j < qty; j++) txn.Items.Add(item.DeepCopy()); } if (!string.IsNullOrEmpty(d["gc_xml"])){ txn.ProcessorXml = new XmlDocument(); txn.ProcessorXml.LoadXml(d.Pluck("gc_xml")); } txn.Other = d; //All transactions go through TransactionController using (var basket = BasketWrapper.CreateNewByVendor(dataContextFactory, vendorId)) { base.ProcessTransaction(txn.ToTransactionRequest(dataContextFactory), basket); } return new HttpResponseMessage(HttpStatusCode.OK); }
public TransactionItem DeepCopy() { var c = new TransactionItem(); c.ItemName = ItemName; c.SkuString = SkuString; c.Gross = Gross; c.Options = new List<KeyValuePair<string, string>>(); foreach (var p in Options) c.Options.Add(new KeyValuePair<string, string>(p.Key, p.Value)); return c; }
private Payment CreatePayment(APIContext apiContext, string returnUrl, string cancelUrl, Models.Transaction t) { //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List<PayPal.Api.Item>() }; decimal tax = 0, shipping = 0; decimal t_subtotes = 0; List<CartItemViewModel> l_civm = (List<CartItemViewModel>)Session["Cart"]; /* Insert Transaction To Database; Set Status to 1 (NotPaid) Make sure to create TransactionItems */ foreach (CartItemViewModel civm in l_civm) { TransactionItem ti = new TransactionItem(); ti.transaction_id = t.id; ti.item_name = civm.name; ti.item_price = civm.price; ti.quantity = civm.quantity; db.TransactionItems.Add(ti); itemList.items.Add(new PayPal.Api.Item() { name = civm.name, currency = "USD", price = Math.Round(civm.price, 2).ToString(), quantity = civm.quantity.ToString(), sku = civm.id.ToString() }); t_subtotes += civm.price * civm.quantity; // similar as we did for credit card, do here and create details object } var totes = tax + shipping + t_subtotes; var payer = new Payer() { payment_method = "paypal" }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = cancelUrl, return_url = returnUrl }; var details = new Details() { tax = Math.Round(tax, 2).ToString(), shipping = Math.Round(shipping, 2).ToString(), subtotal = Math.Round(t_subtotes, 2).ToString() }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "USD", total = Math.Round(totes, 2).ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; var transactionList = new List<PayPal.Api.Transaction>(); transactionList.Add(new PayPal.Api.Transaction() { description = "Transaction description.", invoice_number = Session["User"].ToString() + "-" + DateTime.Now.ToString("yyyyMMddHHmmss"), amount = amount, item_list = itemList }); this.payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return this.payment.Create(apiContext); }
bool ConsumeTransaction(DirtyData dirtyData, TransactionItem <CoreOperation> coreItem) { var operation = coreItem.Transaction; var validation = coreItem.Validation; if (operation.OperationId <= LastProcessedTransactionId) { return(false); } var type = operation.CoreOperationType; if (type == CoreOperationTypes.Account) { var ar = operation as AccountOperation; { var ac = GetCoreAccount(ar.AccountId, false); if (ac != null) { return(false); } } var account = new CoreAccount(ar.AccountId, ar.PublicKey) { LastTransactionId = operation.OperationId }; lock (_lock) _accounts[account.AccountId] = account; _accountStorage.AddEntry(ar.AccountId, account.ToByteArray()); return(true); } if (type == CoreOperationTypes.ChainInfo) { var co = operation as ChainInfoOperation; { var ci = GetChainInfo(co.ChainId, false); if (co.IsNewChain && ci != null) { return(false); } if (!co.IsNewChain && ci == null) { return(false); } } ChainInfo chain; if (co.IsNewChain) { chain = new ChainInfo(co.ChainId, co.AccountId, co.Name, co.Website); } else { chain = GetChainInfo(co.ChainId); chain.UpdateInfo(co.Name, co.Website); } if (chain.ChainId != Protocol.CoreChainId) { var account = GetCoreAccount(co.AccountId); if (account == null) { return(false); } account.LastTransactionId = operation.OperationId; dirtyData.DirtyAccounts.Add(account.AccountId); } foreach (var endpoint in co.PublicEndpoints) { chain.AddPublicEndPoint(endpoint); } foreach (var endpoint in co.RemovePublicEndPoints) { chain.RemovePublicEndPoint(endpoint); } foreach (var chainKey in co.ChainKeys) { chain.AddChainKey(chainKey, co.Timestamp); } foreach (var chainKeyIndex in co.RevokeChainKeys) { chain.RevokeChainKey(chainKeyIndex, operation.Timestamp); } foreach (var purchase in co.Purchases) { chain.AddPurchase(purchase, co.Timestamp); } foreach (var item in co.RemovePurchaseItems) { chain.RemovePurchaseItem(item, operation.Timestamp); } lock (_lock) _chains[chain.ChainId] = chain; if (co.IsNewChain) { _chainInfoStorage.AddEntry(co.ChainId, chain.ToByteArray()); } else { dirtyData.DirtyChains.Add(co.ChainId); } return(true); } if (type == CoreOperationTypes.Revenue) { var rev = operation as ChainRevenueInfoOperation; var chainId = rev.ChainId; var chain = GetChainInfo(chainId); if (chain == null) { return(false); } chain.AddRevenueInfo(rev.Revenue, rev.RevenueAccountFactor, rev.Timestamp); dirtyData.DirtyChains.Add(chainId); return(true); } if (type == CoreOperationTypes.AccountUpdate) { var u = operation as AccountUpdateOperation; foreach (var item in u.Updates.Values) { var account = GetCoreAccount(item.AccountId, true); if (account == null) { return(false); } account.UpdateBalance(item.Balance); account.LastTransactionId = operation.OperationId; dirtyData.DirtyAccounts.Add(item.AccountId); foreach (var revenue in item.Revenues) { var chainId = revenue.ChainId; var c = GetChainInfo(chainId); c.AddTotalAccountPayout(revenue.Amount); dirtyData.DirtyChains.Add(chainId); } } return(true); } if (type == CoreOperationTypes.BlockState) { var bi = operation as BlockStateOperation; foreach (var state in bi.BlockStates.Values) { var chainId = state.ChainId; var chainInfo = GetChainInfo(chainId); if (chainInfo == null) { return(false); } chainInfo.Update(state); dirtyData.DirtyChains.Add(chainId); } return(true); } return(false); }
public void testTrackEcommerceTransaction() { using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create()) { ShimHttpWebRequest.AllInstances.GetResponse = fake; var t = new Tracker(new Emitter("d3rkrsqld9gmqf.cloudfront.net")); var hat = new TransactionItem("pbz0026", 20, 1); var shirt = new TransactionItem("pbz0038", 15, 1, "shirt", "clothing"); var items = new List<TransactionItem> { hat, shirt }; t.TrackEcommerceTransaction("6a8078be", 35, "affiliation", 3, 0, "Phoenix", "Arizona", "US", "USD", items); var expectedTransaction = new Dictionary<string, string> { {"e", "tr"}, {"tr_id", "6a8078be"}, {"tr_tt", "35"}, {"tr_af", "affiliation"}, {"tr_tx", "3"}, {"tr_sh", "0"}, {"tr_ci", "Phoenix"}, {"tr_st", "Arizona"}, {"tr_co", "US"}, {"tr_cu", "USD"} }; var expectedHat = new Dictionary<string, string> { {"e", "ti"}, {"ti_id", "6a8078be"}, {"ti_sk", "pbz0026"}, {"ti_pr", "20"}, {"ti_qu", "1"}, {"ti_cu", "USD"} }; var expectedShirt = new Dictionary<string, string> { {"e", "ti"}, {"ti_id", "6a8078be"}, {"ti_sk", "pbz0038"}, {"ti_pr", "15"}, {"ti_qu", "1"}, {"ti_nm", "shirt"}, {"ti_ca", "clothing"}, {"ti_cu", "USD"} }; checkResult(expectedTransaction, payloads[payloads.Count - 3]); checkResult(expectedHat, payloads[payloads.Count - 2]); checkResult(expectedShirt, payloads[payloads.Count - 1]); } }
public async Task <Result <List <UserItemExport> > > Handle(Contract request, CancellationToken cancellationToken) { //if (request.UserRole == "Student") // return Result.Fail<List<UserItem>>("Acesso Negado"); var userItems = new List <UserItemExport>(); var currentTransaction = new TransactionItem(); var currentProduct = new EcommerceResponse(); //int i = 0; //int k = 0; var emailsNaoEncontrados = new List <string>(); string[] emails = new string[] { "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" , "*****@*****.**" }; try { for (int i = 0; i < emails.Length; i++) { var dbStudents = await _db.UserCollection .AsQueryable() .Where(x => x.Email.ToLower() == emails[i].ToLower()) .FirstOrDefaultAsync(cancellationToken: cancellationToken); if (dbStudents == null) { emailsNaoEncontrados.Add(emails[i]); continue; } if (dbStudents.ModulesInfo != null) { for (var k = 0; k < dbStudents.ModulesInfo.Count; k++) { userItems.Add(new UserItemExport { Email = dbStudents.Email, Curso = dbStudents.ModulesInfo[k].Name }); } } if (dbStudents.TracksInfo != null) { for (var k = 0; k < dbStudents.TracksInfo.Count; k++) { userItems.Add(new UserItemExport { Email = dbStudents.Email, Curso = dbStudents.TracksInfo[k].Name }); } } } //var transactions = new List<TransactionItem>(); //var response = await PagarMe.GetTransactions(_configuration); //if (response.StatusCode == HttpStatusCode.OK) //{ // var content = await response.Content.ReadAsStringAsync(); // //var parsed = JObject.Parse(content); // transactions = JsonConvert.DeserializeObject<List<TransactionItem>>( // content // ); //} //else //{ // string content = await response.Content.ReadAsStringAsync(); // //await CreateErrorLog("transaction-not-found", content, cancellationToken); //} //for (i = 0; i < transactions.Count; i++) //{ // currentTransaction = transactions[i]; // var orderResp = await Woocommerce.GetOrderById(transactions[i].metadata.order_number, _configuration); // var product = new EcommerceResponse(); // if (orderResp.StatusCode == HttpStatusCode.OK) // { // var content = await orderResp.Content.ReadAsStringAsync(); // //var parsed = JObject.Parse(content); // product = JsonConvert.DeserializeObject<EcommerceResponse>( // content // ); // currentProduct = product; // } // //else // //{ // // continue; // // //string content = await response.Content.ReadAsStringAsync(); // // //await CreateErrorLog("transaction-not-found", content, cancellationToken); // //} // userItems.Add(new UserItemExport // { // aluno_nome = transactions[i].customer != null ? transactions[i].customer.name : "", // matricula_data = transactions[i].formated_date_created, // plapagamento_id = transactions[i].payment_method, // turma_data_inicio = transactions[i].formated_date_created, // curso_nome = product.order != null ? product.order.line_items[0].name : "" // }); //var dbStudents = await _db.UserCollection // .AsQueryable() // .Where(x => (x.ModulesInfo != null && x.ModulesInfo.Count > 0) // || (x.TracksInfo != null && x.TracksInfo.Count > 0)) // .ToListAsync(cancellationToken: cancellationToken); //for (i = 0; i < dbStudents.Count; i++) //{ // if (dbStudents[i].ModulesInfo != null) // { // for (k = 0; k < dbStudents[i].ModulesInfo.Count; k++) // { // userItems.Add(new UserItemExport // { // aluno_nome = dbStudents[i].Name, // matricula_data = dbStudents[i].ModulesInfo[k].CreatedAt != null ? // dbStudents[i].ModulesInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") : // dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"), // turma_data_inicio = dbStudents[i].ModulesInfo[k].CreatedAt != null ? // dbStudents[i].ModulesInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") : // dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"), // plapagamento_id = "X", // curso_nome = dbStudents[i].ModulesInfo[k].Name // }); // } // } // if (dbStudents[i].TracksInfo != null) // { // for (k = 0; k < dbStudents[i].TracksInfo.Count; k++) // { // userItems.Add(new UserItemExport // { // aluno_nome = dbStudents[i].Name, // matricula_data = dbStudents[i].TracksInfo[k].CreatedAt != null ? // dbStudents[i].TracksInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") : // dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"), // turma_data_inicio = dbStudents[i].TracksInfo[k].CreatedAt != null ? // dbStudents[i].TracksInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") : // dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"), // plapagamento_id = "X", // curso_nome = dbStudents[i].TracksInfo[k].Name // }); // } // } //} //var dbEvents = await _db.EventCollection // .AsQueryable() // .Where(x => eventsIds.Contains(x.Id)) // .Select(x => new RelationalItem // { // Id = x.Id, // Name = x.Title // }) // .ToListAsync(cancellationToken: cancellationToken); //} var emailsString = string.Join(";", emailsNaoEncontrados); return(Result.Ok(userItems.ToList())); } catch (Exception ex) { //var iError = i; //var kError = k; //var errorTransaction = currentTransaction; //var errorProduct = currentProduct; return(Result.Fail <List <UserItemExport> >("Acesso Negado")); } }
/// <summary> /// Retrieve an array of <see cref="PartitionChange"/> structures /// based on the sepcified <see cref="TransactionItem"/> /// </summary> public static PartitionChange[] GetPartitionChanges(TransactionItem transactionItem) { return TransactionItemGetPartitionChanges(transactionItem); }
private void BtnCheckout_Click(object sender, RoutedEventArgs e) { string jumlahDibayar = TxtJumlahDibayar.Text; int totalPrice = Convert.ToInt32(jumlahDibayar); string bayar = TxtJumlahPembayaran.Text; int jumlahPembayaran = Convert.ToInt32(bayar); int kembalian = jumlahPembayaran - totalPrice; if (jumlahPembayaran < totalPrice) { MessageBox.Show("Uang yg dibayar kurang!"); } else { var pushTransaction = new Transaction(jumlahPembayaran, DateTime.Now); myContext.Transactions.Add(pushTransaction); var resultTransaction = myContext.SaveChanges(); string transacId = pushTransaction.Id.ToString(); int transactionId = Convert.ToInt32(transacId); foreach (var result in traItem) { string transId = pushTransaction.Id.ToString(); int transIdPush = Convert.ToInt32(transId); var getDataTransaction = myContext.Transactions.Where(o => o.Id == transIdPush).First(); string itemId = result.Item.Id.ToString(); int itemIdPush = Convert.ToInt32(itemId); var getDataItem = myContext.Items.Where(o => o.Id == itemIdPush).First(); string qtyPush = result.Qty.ToString(); int qtyToPush = Convert.ToInt32(qtyPush); string totalPricePush = result.TotalPrice.ToString(); int totalPriceToPush = Convert.ToInt32(totalPrice); var pushTransactionItem = new TransactionItem(qtyToPush, totalPriceToPush, getDataTransaction, getDataItem); myContext.TransactionItems.Add(pushTransactionItem); var resultTransactionItem = myContext.SaveChanges(); var stockItem = myContext.Items.Where(o => o.Id == itemIdPush).Select(o => o.Stock).First(); int afterStock = stockItem - qtyToPush; var updateItem = myContext.Items.Where(o => o.Id == itemIdPush).First(); updateItem.Stock = afterStock; var modifyItem = myContext.SaveChanges(); if (resultTransactionItem > 0 && modifyItem > 0) { MessageBox.Show(resultTransactionItem + " has been inserted and " + modifyItem + " item stock has been updated"); } else { MessageBox.Show("Fail to insert"); } //MessageBox.Show(transId + '|' + itemId + '|' + qtyPush + '|' + totalPricePush); } MessageBox.Show("Kembalian : Rp " + kembalian + ",-"); MessageBoxResult messageBoxResult = MessageBox.Show("Want to print payment invoice?", "Print Confirmation", MessageBoxButton.YesNo); TransactionsGrid.ItemsSource = myContext.TransactionItems.ToList(); ItemShopGrid.ItemsSource = myContext.Items.ToList(); if (messageBoxResult == MessageBoxResult.Yes) { int dockey = Convert.ToInt32(transactionId); FormReportcs formReportcs = new FormReportcs(dockey); formReportcs.Show(); } else { MessageBox.Show("Fail to load payment invoice!"); } } }
/// <summary> /// /// </summary> /// <param name="vendor"></param> /// <param name="postedData"></param> public HttpResponseMessage PostTransactionByIpn([FromUri] string id, [FromBody] FormDataCollection postedData) { var vendorId = Guid.Parse(id); var txn = new Transaction(); var d = postedData.ReadAsNameValueCollection(); //To calculate 'handshake', run 'md5 -s [password]', then 'md5 -s [email protected][Last MD5 result]' string handshakeParameter = d.Pluck("handshake", null); if (handshakeParameter == null) { throw new Exception("Missing parameter 'handshake'."); } using (var dataContext = dataContextFactory.Create()) { var vendor = dataContext.Vendors.Where(v => v.ObjectId == vendorId) .Include(v => v.VendorCredentials) .FirstOrDefault(); if (vendor == null) { throw new Exception("Could not find vendor with id: " + vendorId); } string[] vendorCredentials = vendor.VendorCredentials.Select( c => Encoding.UTF8.GetString(SymmetricEncryption.DecryptForDatabase(c.CredentialValue)).ToLower()).ToArray(); if (!vendorCredentials.Contains(handshakeParameter.ToLower())) { throw new Exception("Invalid handshake provided"); } } string txn_id = d.Pluck("txn_id"); //TODO: We must ignore duplicate POSTs with the same txn_id - all POSTs will contain the same information if (!"Completed".Equals(d.Pluck("payment_status"), StringComparison.OrdinalIgnoreCase)) { throw new Exception("Only completed transactions should be sent to this URL"); } //var txn = new Transaction(); txn.VendorId = vendorId; txn.ExternalTransactionId = txn_id; txn.PaymentDate = ConvertPayPalDateTime(d.Pluck("payment_date")); txn.PayerEmail = d.Pluck("payer_email"); txn.PassThroughData = d.Pluck("custom"); txn.Currency = d.Pluck("mc_currency"); txn.InvoiceId = d.Pluck("invoice"); txn.Gross = d.Pluck <double>("mc_gross"); txn.TransactionFee = d.Pluck <double>("mc_fee"); txn.Tax = d.Pluck <double>("tax"); txn.TransactionType = d.Pluck("transaction_type"); if (d["payer_name"] == null) { d["payer_name"] = d["first_name"] + " " + d["last_name"]; } txn.Billing = ParseFrom(d, "payer_"); txn.Shipping = ParseFrom(d, "address_"); var itemCount = d.Pluck <int>("num_cart_items", 1); txn.Items = new List <TransactionItem>(); for (var i = 1; i <= itemCount; i++) { string suffix = i.ToString(); var item = new TransactionItem(); item.Gross = d.Pluck <double>("mc_gross_" + i.ToString()).Value; item.ItemName = d.Pluck("item_name" + i.ToString()); item.SkuString = d.Pluck("item_number" + i.ToString()); item.Options = new List <KeyValuePair <string, string> >(); for (var j = 1; j < 4; j++) { string opt_key = d.Pluck("option_name" + j.ToString() + "_" + i.ToString()); string opt_val = d.Pluck("option_selection" + j.ToString() + "_" + i.ToString()); if (string.IsNullOrEmpty(opt_val)) { continue; } item.Options.Add(new KeyValuePair <string, string>(opt_key, opt_val)); } var qty = d.Pluck <int>("quantity" + i.ToString(), 1).Value; for (var j = 0; j < qty; j++) { txn.Items.Add(item.DeepCopy()); } } if (!string.IsNullOrEmpty(d["gc_xml"])) { txn.ProcessorXml = new XmlDocument(); txn.ProcessorXml.LoadXml(d.Pluck("gc_xml")); } txn.Other = d; //All transactions go through TransactionController using (var basket = BasketWrapper.CreateNewByVendor(dataContextFactory, vendorId)) { base.ProcessTransaction(txn.ToTransactionRequest(dataContextFactory), basket); } return(new HttpResponseMessage(HttpStatusCode.OK)); }
public void RecordTransaction(TransactionDto transaction) { // get the transaction entity var transac = _mapper.Map <Transaction>(transaction); var uniqueDictionary = new Dictionary <int, ItemDto>(); var itemsList = transaction.Items.ToList(); foreach (var itemDto in itemsList) { if (itemDto.ItemId < 0) { var thisItem = _ctx.StockItems.FirstOrDefault(i => i.ItemName == itemDto.ItemName); if (thisItem == null) { throw new Exception("This is a real problem here"); } itemDto.ItemId = thisItem.ItemId; } if (uniqueDictionary.ContainsKey(itemDto.ItemId)) { uniqueDictionary[itemDto.ItemId].Quantity += itemDto.Quantity; continue; } uniqueDictionary.Add(itemDto.ItemId, itemDto); } Console.Write('s'); foreach (var item in uniqueDictionary.Values.ToList()) { var transactionItem = new TransactionItem { Transaction = transac }; // attempt to look for item in db var itemToAdd = _ctx.StockItems.FirstOrDefault(i => i.ItemName == item.ItemName); // if it doesn't exist if (itemToAdd == null) { var newItem = _mapper.Map <Item>(item); switch (transaction.TransactionType) { // if sale, set custom quantity case 1: newItem.Quantity = 0; transactionItem.Item = newItem; break; // if purchase, add as is case 0: transactionItem.Item = newItem; break; default: throw new KeyNotFoundException("invalid transaction type"); } _ctx.TransactionItems.Add(transactionItem); // if it does exist, update its quantity } else if (transaction.TransactionType == 1) { // if sale, subtract quantity from items table,leave all others intact // TO-DO: find a better way to do this, maybe a partial model that updates // only the properties i want updated itemToAdd.Quantity -= item.Quantity; _ctx.Entry(itemToAdd).State = EntityState.Modified; // do i need these? _ctx.Entry(itemToAdd).Property(x => x.Unit).IsModified = false; _ctx.Entry(itemToAdd).Property(x => x.SellingPrice).IsModified = false; _ctx.Entry(itemToAdd).Property(x => x.PurchaseCost).IsModified = false; transactionItem.Item = itemToAdd; // update transasctionItem's other fields: quantity and amount transactionItem.Quantity = item.Quantity; transactionItem.Amount = item.Quantity * item.SellingPrice; _ctx.TransactionItems.Add(transactionItem); } else { // if purchase, add quantity, update purchase field, leave all others intact itemToAdd.Quantity += item.Quantity; itemToAdd.PurchaseCost += item.PurchaseCost; _ctx.Entry(itemToAdd).State = EntityState.Modified; _ctx.Entry(itemToAdd).Property(x => x.Unit).IsModified = false; _ctx.Entry(itemToAdd).Property(x => x.SellingPrice).IsModified = false; _ctx.Entry(itemToAdd).Property(x => x.PurchaseCost).IsModified = false; transactionItem.Item = itemToAdd; // update transasctionItem's other fields: quantity and amount transactionItem.Quantity = item.Quantity; transactionItem.Amount = item.Quantity * item.PurchaseCost; _ctx.TransactionItems.Add(transactionItem); } } _ctx.Transactions.Add(transac); _ctx.SaveChanges(); }
private void GetStockTransactionsForProduct() { Location selectedLocation = cbLocations.SelectedItem as Location; ProductItem product = cbStockItems.SelectedItem as ProductItem; if (selectedLocation != null && product != null) { if (datePickerStart.SelectedDate.HasValue && datePickerEnd.SelectedDate.HasValue) { DateTime start = datePickerStart.SelectedDate.Value; DateTime end = datePickerEnd.SelectedDate.Value; if (selectedLocation.Id != ObjectId.Empty) { var items = DbManager.GetInstance().GetStockTransactionsForProductAtLocationAndInterval(selectedLocation.Id, product.ProductId, start, end); if (items != null) { CreateStockReportForProduct(items); } else { TransactionItem lastTransaction = DbManager.GetInstance().GetLatestStockTransactionForProductAtLocation(selectedLocation.Id, product.ProductId); string message = ""; if (lastTransaction != null) { message = "Latest stock quanity was: " + lastTransaction.StartingStockAmount + " at " + lastTransaction.TimeStamp; } ClearAnalytics(); MessageBox.Show("No stock transactions took place for product in interval. " + message); } } else { var items = DbManager.GetInstance().GetStockTransactionsForProductInInterval(product.ProductId, start, end); if (items != null) { CreateStockReportForProduct(items); } else { TransactionItem lastTransaction = DbManager.GetInstance().GetLatestStockTransactionForProduct(product.ProductId); string message = ""; if (lastTransaction != null) { message = "Latest stock quanity was: " + lastTransaction.StartingStockAmount + " at " + lastTransaction.TimeStamp; } ClearAnalytics(); MessageBox.Show("No stock transactions took place for product in interval. " + message); } } } else { MessageBox.Show("Select a valid date interval"); } } else { MessageBox.Show("Select location specification and product name first"); } }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { TransactionItem.CloseDatabase(); }
public void MenuTransaction() { Item item = new Item(); Transaction transaction = new Transaction(); MyContext _context = new MyContext(); TransactionItem transactionItem = new TransactionItem(); //insert master transaction transaction.TransactionDate = DateTimeOffset.Now.LocalDateTime; _context.Transactions.Add(transaction); _context.SaveChanges(); //get id transaction last var getTransaction = _context.Transactions.Max(x => x.Id); var getTransactionDetail = _context.Transactions.Find(getTransaction); Console.WriteLine("Transaction Id : " + getTransaction); Console.WriteLine("Transaction Date : " + getTransactionDetail.TransactionDate); Console.Write("How many items : "); count = Convert.ToInt16(Console.ReadLine()); if (count == null) { Console.WriteLine("Please insert cpunt of item that you want to buy"); Console.Read(); } else { for (int i = 1; i <= count; i++) { Console.Write("Insert id item : "); int?id = Convert.ToInt16(Console.ReadLine()); if (id == null) { Console.WriteLine("Please insert id that you want to buy"); Console.Read(); } else { //Pencarian Id Item var getItem = _context.Items.Find(id); if (getItem == null) { Console.WriteLine("We don't have item wit id : " + id); Console.Read(); } else { Console.Write("Insert amount of item : "); var quantity = Convert.ToInt16(Console.ReadLine()); if (getItem.Stok < quantity) { Console.Write("Stok is not enough, we have " + getItem.Stok); Console.Read(); } else { transactionItem.Transactions = getTransactionDetail; transactionItem.Items = getItem; transactionItem.Quantity = quantity; _context.TransactionItems.Add(transactionItem); _context.SaveChanges(); } } } } var getPrice = _context.TransactionItems.Where(x => x.Transactions.Id == getTransactionDetail.Id).ToList(); int?total = 0; foreach (var proceed in getPrice) { total += (proceed.Quantity * proceed.Items.Price); } Console.WriteLine("Total Price : " + total); Console.Write("Balance : "); int?balance = Convert.ToInt32(Console.ReadLine()); Console.Write("Exchange : " + (balance - total)); Console.Read(); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine(" TRRANSACTION ID " + getTransaction); Console.WriteLine(getTransactionDetail.TransactionDate.Date); Console.WriteLine(getTransactionDetail.TransactionDate.TimeOfDay); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine("Name Quantity Price Total"); Console.WriteLine("-------------------------------------------------------"); var getDatatoDisplay = _context.TransactionItems.Where(x => x.Transactions.Id == getTransactionDetail.Id).ToList(); //var getDatatoDisplay = _context.Items.Where(x => x.IsDelete == false).ToList(); //_context.Transactions.Max(x => x.Id) // var getItemid = _context.Items. // var getDatatoDisplay = _context.TransactionItems.Find.getTransaction.Where(x => x.IsDelete == false)).ToList(); foreach (var tampilin in getDatatoDisplay) { Console.WriteLine("" + tampilin.Items.Name + "\t\t" + tampilin.Quantity + "\t\t" + tampilin.Items.Price + "\t\t" + total); } Console.WriteLine("-------------------------------------------------------"); Console.WriteLine("Total Price : " + total); Console.WriteLine("Balance : " + balance); Console.WriteLine("Exchange : " + (balance - total)); Console.WriteLine("-------------------------------------------------------"); Console.ReadLine(); Console.Read(); //var getDatatoDisplay = _context.Transactions.Where(x => x.IsDelete == false).ToList(); //if (getDatatoDisplay.Count == 0) //{ // Console.Write("No Data in your database"); //} //else //{ // foreach (var tampilin in getDatatoDisplay) // { // Console.WriteLine("========================================================="); // Console.WriteLine("Id :" + tampilin.Id); // Console.WriteLine("Transaction Date :" + tampilin.TransactionDate.DateTime); // Console.WriteLine("Transaction Hour :" + tampilin.TransactionDate.Hour); // Console.WriteLine("========================================================="); // } // Console.Write("Total Supplier " + getDatatoDisplay.Count); //} //Console.Read(); } }
private void dgTransactions_CellEndEdit(object sender, DataGridViewCellEventArgs e) { CalculateTotals(lblTotalAmounts, (List <TransactionItem>)dgTransactions.DataSource); TransactionItem.GetCollection().Update(((TransactionItem)dgTransactions.Rows[e.RowIndex].DataBoundItem)); }
static async Task Main(string[] args) { Console.WriteLine("Hello World!"); var connectionString = "ConnectTo=tcp://admin:Airfi2018Airfi2018@http://52.151.85.8:1113; HeartBeatTimeout=500"; // var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@http://52.151.85.8:1113") // var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@52.151.85.8:1113") // // ); var conn = EventStoreConnection.Create( ConnectionSettings.Create().KeepReconnecting(), ClusterSettings.Create().DiscoverClusterViaGossipSeeds().SetGossipSeedEndPoints(new [] { new IPEndPoint(IPAddress.Parse("52.151.78.42"), 2113), new IPEndPoint(IPAddress.Parse("52.151.79.84"), 2113), new IPEndPoint(IPAddress.Parse("51.140.14.214"), 2113) }).SetGossipTimeout(TimeSpan.FromMilliseconds(500)).Build()); await conn.ConnectAsync(); // var accountId = $"Account-{Guid.NewGuid()}"; var accountId = "Account-4d4158cd-a6ac-49cf-a41e-d11f86ccbbf6"; // var accountId = "test1"; // await conn.DeleteStreamAsync("Transactions", ExpectedVersion.Any,true); var watch = new Stopwatch(); watch.Start(); var tasks = new List <Task>(); var rnd = new Random(); var props = new List <Dictionary <string, object> >(); // props.Add(new Dictionary<string, object>() {{"item1", "value1"}}); // props.Add(new Dictionary<string, object>() {{"item2", "value2"}}); var subfee1 = new TransactionService.External.ValueObjects.KeyValuePair("myKey", "MyValue"); var companyId = "b3e4bf26-c93b-41f6-adf1-27b85fa82c91"; var subfee2 = new Fee(companyId, "MyLabel", 50, "USD", "0.9", 0, 0); var subfees = new List <Fee>() { subfee2 }; var keyValueParis = new List <TransactionService.External.ValueObjects.KeyValuePair>() { subfee1 }; var item = new TransactionItem(100, "B2C Renewal", 1, keyValueParis, subfees); var transaction = new Transaction("T-00001", Guid.NewGuid().ToString(), "Transaction", "B2C Renewal", 100, 50, new DateTime(rnd.Next(2015, 2018), rnd.Next(1, 12), rnd.Next(1, 28)), 20, "GBR", "GBP", new List <TransactionItem>() { item }); var data = new Data() { Balance = 100, Id = Guid.NewGuid().ToString() }; var jsonBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(new AccountCreditedEvent(transaction), new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() })); for (int j = 0; j < 100; j++) { for (int i = 0; i < 100; i++) { tasks.Add(Task.Run(async() => { var e = new EventData(Guid.NewGuid(), "accountCredited", true, jsonBytes, null); // var conn = EventStoreConnection.Create(new Uri("tcp://*****:*****@localhost:1113") // ); // await conn.ConnectAsync(); await conn.AppendToStreamAsync(accountId, ExpectedVersion.Any, e); })); } // while (tasks.Count != 0) // { //// Thread.Sleep(TimeSpan.FromSeconds(1)); // var ts = tasks.Take(50).ToList(); // ts.ForEach(t => t.Start()); // Task.WaitAll(ts.ToArray()); // // tasks.RemoveAll(t => ts.Contains(t)); // } Task.WaitAll(tasks.ToArray()); } watch.Stop(); Console.WriteLine(watch.Elapsed); Console.ReadLine(); }
/// <inheritdoc /> public override void ModelPropertyChanged(Element modelElement, string propertyName, TransactionItem transactionItem) { base.ModelPropertyChanged(modelElement, propertyName, transactionItem); if (propertyName == "Icon") { // Notify the view that the icon changed NotifyPropertyChanged("Icon"); } }
public void TestCombine() { Parameters param = new Parameters(10.0f, 10.0f, "none", TripType.SingleTrip, 0); TransactionItem pt1 = new TransactionItem(p1, 35); TransactionItem pt2 = new TransactionItem(p1, 25); TransactionItem st1 = new TransactionItem(s1, 35); TransactionItem st2 = new TransactionItem(s1, 25); Transaction t1 = new Transaction(pt1, st1); Transaction t2 = new Transaction(pt2, st2); t1.Combine(t2); Assert.AreEqual(60, t1.Purchases[0].Quantity); Assert.AreEqual(60, t1.Sales[0].Quantity); }
public static TR Map <T, TR>(T sourceObject) where T : class where TR : class { if (sourceObject == null) { return(null); } Type myType = typeof(T); if (myType == typeof(TransactionItem)) { var objItem = new ExpenseManager.EF.TransactionItem(); var myItem = sourceObject as TransactionItem; if (myItem == null) { return(null); } ; try { objItem.TransactionItemId = myItem.TransactionItemId; objItem.ExpensenseItemId = myItem.ExpensenseItemId; objItem.RequestedQuantity = myItem.RequestedQuantity; objItem.RequestedUnitPrice = myItem.RequestedUnitPrice; objItem.ExpenseTransactionId = myItem.ExpenseTransactionId; objItem.ExpenseCategoryId = myItem.ExpenseCategoryId; objItem.ExpenseTypeId = myItem.ExpenseTypeId; objItem.ApprovedQuantity = myItem.ApprovedQuantity; objItem.ApprovedUnitPrice = myItem.ApprovedUnitPrice; objItem.ApprovedTotalPrice = myItem.ApprovedTotalPrice; objItem.Description = myItem.Description; objItem.Status = myItem.Status; } catch (Exception ex) { return(new TransactionItem() as TR); } return(objItem as TR); } if (myType == typeof(ExpenseManager.EF.TransactionItem)) { var objItem = new TransactionItem(); var myItem = sourceObject as ExpenseManager.EF.TransactionItem; if (myItem == null) { return(null); } ; try { objItem.TransactionItemId = myItem.TransactionItemId; objItem.ExpensenseItemId = myItem.ExpensenseItemId; objItem.RequestedQuantity = myItem.RequestedQuantity; objItem.RequestedUnitPrice = myItem.RequestedUnitPrice; objItem.ExpenseTransactionId = myItem.ExpenseTransactionId; objItem.ExpenseCategoryId = myItem.ExpenseCategoryId; objItem.ExpenseTypeId = myItem.ExpenseTypeId; objItem.ApprovedQuantity = myItem.ApprovedQuantity; objItem.ApprovedUnitPrice = myItem.ApprovedUnitPrice; objItem.ApprovedTotalPrice = myItem.ApprovedTotalPrice; objItem.Description = myItem.Description; objItem.Status = myItem.Status; #region Included Tables try { objItem.ExpenseItem = new ExpenseItem(); objItem.ExpenseItem.ExpenseItemId = myItem.ExpenseItem.ExpenseItemId; objItem.ExpenseItem.ExpenseCategoryId = myItem.ExpenseItem.ExpenseCategoryId; objItem.ExpenseItem.AccountsHeadId = myItem.ExpenseItem.AccountsHeadId; objItem.ExpenseItem.Title = myItem.ExpenseItem.Title; objItem.ExpenseItem.Description = myItem.ExpenseItem.Description; objItem.ExpenseItem.Code = myItem.ExpenseItem.Code; objItem.ExpenseItem.Status = myItem.ExpenseItem.Status; } catch {} try { objItem.ExpenseTransaction = new ExpenseTransaction(); objItem.ExpenseTransaction.ExpenseTransactionId = myItem.ExpenseTransaction.ExpenseTransactionId; objItem.ExpenseTransaction.ExpenseTitle = myItem.ExpenseTransaction.ExpenseTitle; objItem.ExpenseTransaction.Description = myItem.ExpenseTransaction.Description; objItem.ExpenseTransaction.BeneficiaryId = myItem.ExpenseTransaction.BeneficiaryId; objItem.ExpenseTransaction.BeneficiaryTypeId = myItem.ExpenseTransaction.BeneficiaryTypeId; objItem.ExpenseTransaction.RegisteredById = myItem.ExpenseTransaction.RegisteredById; objItem.ExpenseTransaction.TransactionDate = myItem.ExpenseTransaction.TransactionDate; objItem.ExpenseTransaction.TransactionTime = myItem.ExpenseTransaction.TransactionTime; objItem.ExpenseTransaction.Status = myItem.ExpenseTransaction.Status; objItem.ExpenseTransaction.TotalTransactionAmount = myItem.ExpenseTransaction.TotalTransactionAmount; objItem.ExpenseTransaction.ApproverId = myItem.ExpenseTransaction.ApproverId; objItem.ExpenseTransaction.DateApproved = myItem.ExpenseTransaction.DateApproved; objItem.ExpenseTransaction.TimeApproved = myItem.ExpenseTransaction.TimeApproved; objItem.ExpenseTransaction.TotalApprovedAmount = myItem.ExpenseTransaction.TotalApprovedAmount; objItem.ExpenseTransaction.ApproverComment = myItem.ExpenseTransaction.ApproverComment; } catch {} try { objItem.ExpenseCategory = new ExpenseCategory(); objItem.ExpenseCategory.ExpenseCategoryId = myItem.ExpenseCategory.ExpenseCategoryId; objItem.ExpenseCategory.Title = myItem.ExpenseCategory.Title; objItem.ExpenseCategory.Code = myItem.ExpenseCategory.Code; objItem.ExpenseCategory.Status = myItem.ExpenseCategory.Status; } catch {} try { objItem.ExpenseType = new ExpenseType(); objItem.ExpenseType.ExpenseTypeId = myItem.ExpenseType.ExpenseTypeId; objItem.ExpenseType.Name = myItem.ExpenseType.Name; objItem.ExpenseType.Status = myItem.ExpenseType.Status; } catch {} #endregion } catch (Exception ex) { return(new TransactionItem() as TR); } return(objItem as TR); } return(null); }
public async Task SendTransactionAsync(string sku, string name, string transactionId, long costPerProduct, int quantity = 1) { if (!IsEnabled) { return; } var transaction = new Transaction(transactionId, costPerProduct * quantity); var item = new TransactionItem(sku, name, costPerProduct, quantity); transaction.Items.Add(item); await InvokeAsync(() => { Log.Debug("Tracking transaction: {0} | {1} | {2} | {3} | {4}", sku, name, transactionId, costPerProduct, quantity); _tracker.SendTransaction(transaction); }); }
public void TestCaseSetUp() { trans = new TransactionItem(t1); }
/// <summary> /// This method is called when the channel itself is changed /// </summary> /// <param name="transactionItem">Information about the change in the model</param> /// <param name="owningScreen">Screen which owns this control</param> /// <param name="channelChangeHandler">The handler to use for registering with the gateway. Since we have two different channels /// we must make sure to provide the gateway with the correct handler</param> private async Task HandleChannelChangeAsync( TransactionItem transactionItem, ScreenModel owningScreen, Action <ITagValue> channelChangeHandler) { var propertyExpressionTransactionItem = transactionItem as PropertyExpressionTransactionItem; // Lots of conditions where we ignore the channel change if (propertyExpressionTransactionItem == null || Host.ActiveRunTimeServiceProvider().Status != RunTimeProviderStatus.Connected || Equals(propertyExpressionTransactionItem.OldValue, propertyExpressionTransactionItem.NewValue) || owningScreen == null) { return; } // The oldValue can be thought of as what the channel value currently is and the newValue is what it will become. string oldValue, newValue; // transaction state being rolled back means that we are undoing something. for our purposes this reverses the logic for which item in the transaction is the old value and which is the new value if (transactionItem.State == TransactionState.RolledBack) { oldValue = propertyExpressionTransactionItem.NewValue as string; newValue = propertyExpressionTransactionItem.OldValue as string; } else { oldValue = propertyExpressionTransactionItem.OldValue as string; newValue = propertyExpressionTransactionItem.NewValue as string; } if (CheckForVectorChannels(!string.IsNullOrEmpty(newValue) ? newValue : oldValue)) { return; } // Depending on whether there are values for old value and new value, either register, unregister, or rebind (which is unregister and register). Rebind is used to avoid // some race conditions with registration when the same control is being unregistered and re-registered to something else if (!string.IsNullOrEmpty(oldValue)) { try { await Host.GetRunTimeService <ITagService>().UnregisterTagAsync(oldValue, channelChangeHandler); } catch (Exception ex) when(ShouldExceptionBeCaught(ex)) { ReportErrorToModel(ex); } } if (!string.IsNullOrEmpty(newValue)) { try { await Host.GetRunTimeService <ITagService>().UnregisterTagAsync(newValue, channelChangeHandler); } catch (Exception ex) when(ShouldExceptionBeCaught(ex)) { ReportErrorToModel(ex); } } }
public int AddTransactionItem(TransactionItem item) { item.Id = _transactionItemId++; _transactionItems.Add(item.Id, item.Clone()); return(item.Id); }
public async Task <SagaState> OrchestrateAsync(TransactionItem input, IDurableOrchestrationContext context, ILogger log) { bool sagaSatePersisted = await SagaStatePersisters[nameof(SagaState.Pending)](); if (!sagaSatePersisted) { return(SagaState.Fail); } ActivityResult <ProducerResult> validateTransferCommandResult = await CommandProducers[nameof(ValidateTransferCommand)](); if (!validateTransferCommandResult.Valid) { await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } string validatorEventName = await DurableOrchestrationContextExtensions .WaitForExternalEventWithTimeout <string>(context, Sources.Validator, ValidatorTimeout); if (validatorEventName != nameof(TransferValidatedEvent)) { log.LogError(string.Format(ConstantStrings.DurableOrchestratorErrorMessage, validatorEventName, Sources.Validator, context.InstanceId)); await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } ActivityResult <ProducerResult> transferCommandResult = await CommandProducers[nameof(TransferCommand)](); if (!transferCommandResult.Valid) { await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } string transferEventName = await DurableOrchestrationContextExtensions .WaitForExternalEventWithTimeout <string>(context, Sources.Transfer, TransferTimeout); if (transferEventName != nameof(TransferSucceededEvent)) { log.LogError(string.Format(ConstantStrings.DurableOrchestratorErrorMessage, transferEventName, Sources.Transfer, context.InstanceId)); await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } ActivityResult <ProducerResult> issueReceiptCommandResult = await CommandProducers[nameof(IssueReceiptCommand)](); if (!issueReceiptCommandResult.Valid) { await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } string receiptEventName = await DurableOrchestrationContextExtensions .WaitForExternalEventWithTimeout <string>(context, Sources.Receipt, ReceiptTimeout); if (receiptEventName != nameof(ReceiptIssuedEvent)) { log.LogError(string.Format(ConstantStrings.DurableOrchestratorErrorMessage, receiptEventName, Sources.Receipt, context.InstanceId)); ActivityResult <ProducerResult> cancelTransferCommandResult = await CommandProducers[nameof(CancelTransferCommand)](); if (!cancelTransferCommandResult.Valid) { await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } string compensatedTransferEventName = await DurableOrchestrationContextExtensions .WaitForExternalEventWithTimeout <string>(context, Sources.Transfer, TransferTimeout); if (compensatedTransferEventName == nameof(TransferCanceledEvent)) { await SagaStatePersisters[nameof(SagaState.Cancelled)](); return(SagaState.Cancelled); } await SagaStatePersisters[nameof(SagaState.Fail)](); return(SagaState.Fail); } await SagaStatePersisters[nameof(SagaState.Success)](); log.LogInformation($@"Saga '{context.InstanceId}' finished successfully."); return(SagaState.Success); }
public void TestPurchase() { var workspace = PrepareMenu("c:\\sd2.txt"); var iskender = workspace.Single <MenuItem>(x => x.Name.ToLower().Contains("iskender")); iskender.Portions[0].MenuItemId = iskender.Id; Assert.IsTrue(workspace.All <MenuItem>().Count() > 0); Assert.IsNotNull(iskender); Assert.IsTrue(iskender.Portions.Count == 1); var donerEti = new InventoryItem { Name = "Döner Eti", BaseUnit = "GR", GroupCode = "", TransactionUnit = "KG", TransactionUnitMultiplier = 1000 }; var yogurt = new InventoryItem { Name = "Yoğurt", BaseUnit = "GR", GroupCode = "", TransactionUnit = "KG", TransactionUnitMultiplier = 1000 }; var pide = new InventoryItem { Name = "Pide", BaseUnit = "Yarım", GroupCode = "", TransactionUnit = "Adet", TransactionUnitMultiplier = 2 }; workspace.Add(donerEti); workspace.Add(yogurt); workspace.Add(pide); var rp = new Recipe { Name = "İskender Reçetesi", Portion = iskender.Portions[0] }; workspace.Add(rp); rp.RecipeItems.Add(new RecipeItem { InventoryItem = donerEti, Quantity = 120 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = yogurt, Quantity = 50 }); rp.RecipeItems.Add(new RecipeItem { InventoryItem = pide, Quantity = 2 }); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); var transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 16, Quantity = 10, Unit = "KG" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = pide, Multiplier = 2, Price = 1, Quantity = 50, Unit = "Adet" }); transaction.TransactionItems.Add(new TransactionItem { InventoryItem = yogurt, Multiplier = 1000, Price = 4, Quantity = 30, Unit = "KG" }); var transactionTotal = transaction.TransactionItems.Sum(x => x.Price * x.Quantity); Assert.AreEqual(transactionTotal, (16 * 10) + (50 * 1) + (30 * 4)); var ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); var transaction2 = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction2); transaction2.TransactionItems.Add(new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 15, Quantity = 10, Unit = "KG" }); var pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var etpc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); Assert.IsNotNull(etpc); Assert.AreEqual(etpc.InStock, 0); Assert.AreEqual(etpc.Purchase, 20); Assert.AreEqual(etpc.Consumption, 0.24m); Assert.AreEqual(etpc.Cost, 15.5m); var yogurtpc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == yogurt.Id); Assert.IsNotNull(yogurtpc); Assert.AreEqual(yogurtpc.InStock, 0); Assert.AreEqual(yogurtpc.Purchase, 30); Assert.AreEqual(yogurtpc.Consumption, 0.1m); var pidepc = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == pide.Id); Assert.IsNotNull(pidepc); Assert.AreEqual(pidepc.InStock, 0); Assert.AreEqual(pidepc.Purchase, 50); Assert.AreEqual(pidepc.Consumption, 2); Assert.AreEqual(pc.CostItems.Count(), 1); AppServices.MainDataContext.StopWorkPeriod(""); Thread.Sleep(1); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); Thread.Sleep(1); transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); const int etAlimMiktari = 50; var ti = new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 12, Quantity = etAlimMiktari, Unit = "KG" }; transaction.TransactionItems.Add(ti); ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var etpc2 = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); Assert.IsNotNull(etpc2); Assert.AreEqual(etpc2.InStock, etpc.GetInventoryPrediction()); Assert.AreEqual(etpc2.Purchase, etAlimMiktari); Assert.AreEqual(etpc2.GetInventoryPrediction(), etpc.GetInventoryPrediction() + etAlimMiktari - 0.24m); var cost = ((etpc.Cost * etpc.GetInventoryPrediction()) + (ti.Price * ti.Quantity)) / (etpc2.InStock + etpc2.Purchase); cost = decimal.Round(cost, 2); Assert.AreEqual(etpc2.Cost, cost); AppServices.MainDataContext.StopWorkPeriod(""); Thread.Sleep(1); AppServices.MainDataContext.StartWorkPeriod("", 0, 0, 0); Thread.Sleep(1); transaction = new Transaction { Date = DateTime.Now, Name = "1" }; workspace.Add(transaction); ti = new TransactionItem { InventoryItem = donerEti, Multiplier = 1000, Price = 10, Quantity = etAlimMiktari, Unit = "KG" }; transaction.TransactionItems.Add(ti); ticket = new Ticket(); workspace.Add(ticket); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); ticket.AddTicketItem(0, iskender, iskender.Portions[0].Name); pc = InventoryService.GetCurrentPeriodicConsumption(workspace); workspace.Add(pc); var etpc3 = pc.PeriodicConsumptionItems.Single(x => x.InventoryItem.Id == donerEti.Id); Assert.IsNotNull(etpc3); Assert.AreEqual(etpc3.InStock, etpc2.GetInventoryPrediction()); Assert.AreEqual(etpc3.Purchase, etAlimMiktari); Assert.AreEqual(etpc3.GetInventoryPrediction(), etpc2.GetInventoryPrediction() + etAlimMiktari - 0.24m); cost = ((etpc2.Cost * etpc2.GetInventoryPrediction()) + (ti.Price * ti.Quantity)) / (etpc3.InStock + etpc3.Purchase); cost = decimal.Round(cost, 2); Assert.AreEqual(etpc3.Cost, cost); }
public void ReIndex() { writerInUse = true; using (var repository = new TradelrRepository()) { // get subdomains var subdomains = repository.GetSubDomains(); foreach (var subdomain in subdomains) { // index contacts writer = CreateWriter(LuceneIndexType.CONTACTS, subdomain.name); if (writer != null) { var contacts = repository.GetAllContacts(subdomain.id); foreach (var contact in contacts) { try { var action = new ContactItem(contact); var doc = IndexContact(action); writer.AddDocument(doc); } catch (Exception ex) { Syslog.Write(ex); } } writer.Optimize(); CloseWriter(); } // index products writer = CreateWriter(LuceneIndexType.PRODUCTS, subdomain.name); if (writer != null) { var products = repository.GetProducts(subdomain.id); foreach (var product in products) { try { var action = new ProductItem(product); var doc = IndexProduct(action); writer.AddDocument(doc); } catch (Exception ex) { Syslog.Write(ex); } } writer.Optimize(); CloseWriter(); } // orders writer = CreateWriter(LuceneIndexType.TRANSACTION, subdomain.name); if (writer != null) { MASTERsubdomain subdomain1 = subdomain; var orders = repository.GetOrders().Where(x => x.user1.organisation1.subdomain == subdomain1.id); foreach (var order in orders) { try { var acttion = new TransactionItem(order); var doc = IndexTransaction(acttion); writer.AddDocument(doc); } catch (Exception ex) { Syslog.Write("Lucene index error: order ID =" + order.id); Syslog.Write(ex); } } writer.Optimize(); CloseWriter(); } } } writerInUse = false; }
private void ResetTree(TransactionItem transactionItem) { // MSBUG: We should be able to reset the Root branch with the // tree attached to the control, but it is losing subitem expansions // and causes all sorts of drawing problems, so detach and reattach // the tree. VirtualTreeControl control = TreeControl; ITree tree = control.Tree; control.Tree = null; myFilter = null; CancelButton = CloseButton; ClearFilterButton.Enabled = false; tree.Root = new ChangeBranch(transactionItem); control.MultiColumnTree = (IMultiColumnTree)tree; }
public TransactionItem Insert(TransactionItem item) { item.Id = _transactionItemRepository.Insert(item); return(item); }
public TransactionItemViewModel(TransactionItem model, IWorkspace workspace) { _workspace = workspace; Model = model; }