CreateTransaction() public method

public CreateTransaction ( string from, string to, decimal value, string type, string paymentMethod, PaymentCard, paymentDetails ) : void
from string
to string
value decimal
type string
paymentMethod string
paymentDetails PaymentCard,
return void
Beispiel #1
0
        public void Post([FromBody] Transaction tx)
        {
            if (!tx.Verify())
            {
                return;
            }

            if (!tx.VerifyWithTxPool(transactionPool))
            {
                return;
            }

            transactionPool.Add(tx);

            if (transactionPool.Count % 3 == 0 && Constants.IsMiner)
            {
                // create generation transaction
                transactionPool.Insert(0, Transaction.CreateTransaction(transactionPool.Sum(a => a.Inputs.Sum(b => b.Amount) - a.Outputs.Sum(c => c.Amount)) + 50m, Constants.PrivateKey, Constants.KnownPublicKeys["Jing"]));

                // create block
                var block = Block.CreateBlock(transactionPool, BlocksController.blockChain, Constants.Difficulty);

                // post api/transactions/  知っているノードすべてに対して
                foreach (var uri in Constants.NodeList)
                {
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(uri);
                        var response = client.PostAsJsonAsync("api/blocks", block).Result;
                    }
                }
            }
        }
Beispiel #2
0
 public TransactionTests(ITestOutputHelper testOutputHelper)
 {
     _testOutputHelper = testOutputHelper;
     _wallet           = new Wallet();
     _transaction      = new Transaction();
     _transaction.CreateTransaction(_wallet, recipientAddress, amountToSend);
 }
Beispiel #3
0
        public void Post([FromBody] Client wallet)
        {
            // Contentsからtransactionを生成
            decimal coin;

            if (!decimal.TryParse(wallet.Coin, out coin))
            {
                return;
            }
            if (!Constants.KnownPublicKeys.ContainsKey(wallet.Receiver))
            {
                return;
            }

            var tx = Transaction.CreateTransaction(BlocksController.blockChain, TransactionsController.transactionPool, Constants.KnownPublicKeys[Constants.ClientName], Constants.KnownPublicKeys[wallet.Receiver], coin, 0.25m, Constants.PrivateKey);

            if (tx.Signature.Length == 0)
            {
                return;
            }

            // post api/transactions/  知っているノードすべてに対して
            foreach (var uri in Constants.NodeList)
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(uri);
                    var response = client.PostAsJsonAsync("api/transactions", tx).Result;
                }
            }
        }
 public TransactionPoolTests(ITestOutputHelper testOutputHelper)
 {
     _testOutputHelper = testOutputHelper;
     _wallet           = new Wallet();
     _transaction      = new Transaction();
     _transaction.CreateTransaction(_wallet, recipientAddress, amountToSend);
     _blockchain = new Features.Blockchain();
 }
Beispiel #5
0
        public void ShouldExceedWalletBalance()
        {
            decimal largeAmount = 40000;

            _transaction           = new Transaction();
            (bool, string)response = _transaction.CreateTransaction(_wallet, recipientAddress, largeAmount);

            Assert.True(response.Item1 == false, response.Item2);
            //_testOutputHelper.WriteLine(response.Item2);
        }
    public bool SendTransaction(string senderAddress, string receiverAddress, CspParameters privateKeyCointainer, int amount)
    {
        Transaction tx = Transaction.CreateTransaction(senderAddress, receiverAddress, privateKeyCointainer, amount, unspentTxOuts, transactionPool);

        if (tx == null)
        {
            return(false);
        }

        return(AddToPool(tx));
    }
Beispiel #7
0
        public Transaction AuthorizeCreditCard(Order order)
        {
            //this is a fake processor for testing...
            //if there are transaction errors,
            //pop them into the TransactionErrors on the Transaction object
            //for display to the end user
            string authCode = System.Guid.NewGuid().ToString().Substring(0, 10);

            Transaction t = Transaction.CreateTransaction(order, authCode, "FakePaymentGateway");

            return(t);
        }
Beispiel #8
0
        public async Task Execute(string filename)
        {
            var workbook = new XSSFWorkbook(filename);

            foreach (var x in Sheets)
            {
                var sheet = workbook.GetSheet(x);

                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    var row = sheet.GetRow(i);

                    var cindex0 = row?.GetCell(0)?.ToString();
                    var cindex1 = row?.GetCell(1)?.ToString();
                    var cindex2 = row?.GetCell(2)?.ToString();
                    var cindex3 = row?.GetCell(3)?.ToString();
                    var cindex4 = row?.GetCell(4)?.ToString();
                    var cindex5 = row?.GetCell(5)?.ToString();
                    var cindex6 = row?.GetCell(6)?.ToString();

                    if (string.IsNullOrEmpty(cindex0) ||
                        string.IsNullOrEmpty(cindex1) ||
                        string.IsNullOrEmpty(cindex2) ||
                        string.IsNullOrEmpty(cindex3) ||
                        string.IsNullOrEmpty(cindex4) ||
                        string.IsNullOrEmpty(cindex5) ||
                        string.IsNullOrEmpty(cindex6))
                    {
                        continue;
                    }

                    var sn          = int.Parse(cindex0);
                    var date        = DateTime.Parse(cindex1);
                    var description = cindex2;
                    var amount      = double.Parse(cindex6);

                    var category = await Category.GetCategoryByName(cindex3);

                    var categoryId = category != null ? category.ID : await Category.CreateCategory(cindex3, cindex3);

                    var subCategory = await SubCategory.GetSubCategoryByName(cindex3, cindex4);

                    var subCategoryId = subCategory != null ? subCategory.ID : await SubCategory.CreateSubCategory(categoryId, cindex4, cindex4);

                    var transactionType = await TransactionType.GetTransactionTypeByName(cindex5);

                    var transactionTypeId = transactionType != null ? transactionType.ID : 0;

                    await Transaction.CreateTransaction(date, description, categoryId, subCategoryId, transactionTypeId, amount);
                }
            }
        }
 public IActionResult AddTransaction(Transaction pTran)
 {
     try {
         Transaction.CreateTransaction(pTran, context);
         return(Ok());
     }
     catch (ForbiddenException e) {
         return(StatusCode(StatusCodes.Status403Forbidden, e.Message));
     }
     catch (NotFoundException e) {
         return(NotFound(e.Message));
     }
 }
Beispiel #10
0
        public IActionResult Create(Transaction transaction)
        {
            if (ModelState.IsValid)
            {
                // 新增交易
                _context.Transaction.Add(transaction);

                // 修改帳戶餘額
                transaction.CreateTransaction(_context);

                _context.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewData["SubTransactionCategoryID"] = new SelectList(_context.SubTransactionCategory, "ID", "SubTransactionCategory", transaction.SubTransactionCategoryID);
            ViewData["UserGroupID"] = new SelectList(_context.UserGroup, "ID", "Name");
            return(View(transaction));
        }
Beispiel #11
0
        static BlocksController()
        {
            var genesis = new Block();

            genesis.Txs.Add(Transaction.CreateTransaction(100m, Constants.GenesisPrivateKey, Constants.KnownPublicKeys["Alice"]));
            genesis.Txs.Add(Transaction.CreateTransaction(50m, Constants.GenesisPrivateKey, Constants.KnownPublicKeys["Alice"]));
            genesis.Txs.Add(Transaction.CreateTransaction(500m, Constants.GenesisPrivateKey, Constants.KnownPublicKeys["Alice"]));
            genesis.Txs.Add(Transaction.CreateTransaction(50m, Constants.GenesisPrivateKey, Constants.KnownPublicKeys["Suzu"]));
            genesis.Txs.Add(Transaction.CreateTransaction(80m, Constants.GenesisPrivateKey, Constants.KnownPublicKeys["White Rabbit"]));

            genesis.Txs.ForEach(a => DigitalSignature.Verify(a.Hash, Constants.KnownPublicKeys["Joe"], a.Signature));

            genesis.PrevHash   = string.Empty;
            genesis.Difficulty = Constants.Difficulty;
            genesis.CalcBlockHash();
            genesis.UpdateTimestamp();
            blockChain.Add(genesis);
        }
Beispiel #12
0
        //{"symbol":"ETHUSD","price":181.85,"ordType":"Limit","execInst":"Close","text":"Position Close from www.bitmex.com"}
        //{"ordType":"Market","orderQty":7000,"side":"Buy","symbol":"ETHUSD","text":"Submission from www.bitmex.com"
        public bool MarketTransaction(Account A, uint Quantity, string Side, string Symbol) //market order chooses price for u, highest by default
        {
            BitMEXApi bitmex = new BitMEXApi(A.APIKey, A.SecretKey);

            Dictionary <string, string> Params = new Dictionary <string, string>();

            Params.Add("ordType", "Market");
            Params.Add("orderQty", Quantity.ToString().Replace("\"", ""));
            Params.Add("side", Side);
            Params.Add("symbol", Symbol);
            Params.Add("text", "Submission from www.bitmex.com");

            try
            {
                if (Side == "Sell")
                {
                    Transaction S      = new Transaction();
                    bool        Result = S.CreateTransaction(A, true, Quantity, Transaction.OrderTypes.Market, Convert.ToDecimal(0.0), Symbol, "Sell");
                }
                else if (Side == "Buy")
                {
                    Transaction L = new Transaction();
                    L.CreateTransaction(A, true, Quantity, Transaction.OrderTypes.Market, Convert.ToDecimal(0.0), Symbol, "Buy");
                }
            }
            catch
            {
                Console.WriteLine("Error on Sell/buy");
                return(false);
            }



            if (Side == "Buy")
            {
            }
            else if (Side == "Sell")
            {
            }

            return(true);
        }
Beispiel #13
0
        public ActionResult Save(string terms, long?id, long orderNumber, decimal?[] tax, long?[] itemid, int[] quantity, decimal[] unitPrice,
                                 string discount, string discountType, int currency,
                                 string shippingMethod, string shippingCost, long receiverOrgID, DateTime orderDate, long location, TransactionType type)
        {
            bool newOrder = !id.HasValue;

            var order_byOrderNumber = repository.GetOrderByOrderNumber(subdomainid.Value, type, orderNumber);

            Transaction transaction;

            if (!newOrder)
            {
                // update
                transaction = new Transaction(repository.GetOrder(subdomainid.Value, id.Value), repository, sessionid.Value);

                if (transaction.GetOrderStatus() != OrderStatus.DRAFT)
                {
                    return(Json("Cannot edit sent orders".ToJsonFail()));
                }

                // verify that order or invoice number does not already exist
                if (order_byOrderNumber != null && order_byOrderNumber.id != id.Value)
                {
                    var msg = string.Format("{0} Number #{1} already in use", type.ToDescriptionString(), orderNumber.ToString("D8"));
                    return(SendJsonErrorResponse(msg));
                }
            }
            else
            {
                if (accountLimits.invoices.HasValue && type == TransactionType.INVOICE)
                {
                    var invoicesThisMonth = repository.GetMonthlyInvoiceCount(sessionid.Value);
                    if (invoicesThisMonth >= accountLimits.invoices.Value)
                    {
                        return(SendJsonErrorResponse("Monthly invoice limit exceeded. Please upgrade your <a href=\"/dashboard/account/plan\">plan</a>."));
                    }
                }

                // create
                var receiver = repository.GetPrimaryUser(receiverOrgID);
                transaction = new Transaction(MASTERdomain, receiver, type, repository, sessionid.Value);
                transaction.CreateTransaction(orderNumber, orderDate.ToUniversalTime(), terms, currency);

                // verify that order or invoice number does not already exist
                if (order_byOrderNumber != null)
                {
                    var msg = string.Format("{0} Number #{1} already in use", type.ToDescriptionString(), orderNumber.ToString("D8"));
                    return(SendJsonErrorResponse(msg));
                }
            }

            var posted_orderitems = new List <orderItem>();

            if (itemid != null)
            {
                for (int i = 0; i < itemid.Length; i++)
                {
                    var id_item = itemid[i];
                    if (!id_item.HasValue)
                    {
                        continue;
                    }
                    var item_quantity = quantity[i];
                    var unit_price    = unitPrice[i];
                    var item          = new orderItem()
                    {
                        quantity  = item_quantity,
                        unitPrice = unit_price,
                        variantid = id_item.Value
                    };

                    // invoice only
                    if (tax != null)
                    {
                        item.tax = tax[i];
                    }

                    // insert into order
                    posted_orderitems.Add(item);
                }
            }

            if (posted_orderitems.Count == 0 || itemid == null)
            {
                return(Json("No items were specified".ToJsonFail()));
            }

            // update fields
            transaction.UpdateCurrency(currency);
            transaction.UpdateDiscount(discountType, discount);
            transaction.UpdateOrderNumber(orderNumber);
            transaction.UpdateShippingCost(shippingCost);
            transaction.UpdateShippingMethod(shippingMethod);
            transaction.UpdateTerms(terms);
            transaction.UpdateInventoryLocation(location);

            // email receiver of change
            if (transaction.GetOrderStatus() != OrderStatus.DRAFT)
            {
                var data = new ChangeHistory
                {
                    documentType = type == TransactionType.INVOICE? ChangeHistoryType.INVOICE.ToDocumentType() : ChangeHistoryType.ORDERS.ToDocumentType(),
                    documentName = transaction.GetOrderNumber(),
                    documentLoc  = accountHostname.ToDomainUrl(transaction.GetOrderLink())
                };

                var message = new Message(transaction.GetReceiver(), transaction.GetOwner(), subdomainid.Value);
                message.SendMessage(this, repository, EmailViewType.INVOICEORDER_CHANGED, data,
                                    data.documentType + " Updated", transaction.GetOrderLink());
            }

            var variants = repository.GetProductVariants(subdomainid.Value).Where(x => itemid.Contains(x.id));

            if (!newOrder)
            {
                // log activity
                repository.AddActivity(sessionid.Value,
                                       new ActivityMessage(transaction.GetID(), transaction.GetReceiver().id,
                                                           type == TransactionType.ORDER? ActivityMessageType.ORDER_UPDATED : ActivityMessageType.INVOICE_UPDATED,
                                                           new HtmlLink(transaction.GetOrderNumber(), transaction.GetID()).ToTransactionString(type)), subdomainid.Value);


                // handle deleted items first
                var orderItemsToDelete = transaction.GetOrderItems().Where(x => !itemid.Contains(x.variantid)).ToArray();

                foreach (var entry in orderItemsToDelete)
                {
                    var oitem = entry;
                    transaction.DeleteOrderItem(oitem);
                }
            }

            // add order items
            foreach (var entry in posted_orderitems)
            {
                var variantid = entry.variantid;

                // try get from existing order
                var existingOrderitem = transaction.GetOrderItems().SingleOrDefault(x => x.variantid == variantid);
                int inventoryDelta;
                if (existingOrderitem == null)
                {
                    // this is a new item so we need to add it
                    var v = variants.Single(x => x.id == variantid);
                    entry.description = v.ToProductFullTitle();

                    transaction.AddOrderItem(entry, v.product.products_digitals);

                    inventoryDelta    = entry.quantity;
                    existingOrderitem = entry;
                }
                else
                {
                    // get delta first
                    inventoryDelta = entry.quantity - existingOrderitem.quantity;

                    existingOrderitem.unitPrice = entry.unitPrice;
                    existingOrderitem.quantity  = entry.quantity;
                    existingOrderitem.tax       = entry.tax;
                }

                transaction.UpdateInventoryItem(existingOrderitem, inventoryDelta);
            }

            transaction.UpdateTotal();
            if (!newOrder)
            {
                transaction.SaveUpdatedTransaction();
            }
            else
            {
                transaction.SaveNewTransaction();
            }

            return(Json(transaction.GetID().ToJsonOKData()));
        }
Beispiel #14
0
        // json is true when checkout is done from an iframe, eg. facebook page
        public ActionResult create(CheckoutStatus status, string shippingmethod, string paymentmethod, bool isJson = false)
        {
            Debug.Assert(!cart.orderid.HasValue);

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

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

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

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

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

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

                shoppingcart.items.Add(checkOutItem);
            }

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

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

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

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

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

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

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

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

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

            repository.Save();

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

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

            string buyer_subject;
            string seller_subject;

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

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

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

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

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

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

            // handle payment
            string redirecturl = "";

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

                default:
                    break;
                }
            }

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

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

            return(RedirectToAction("Index"));
        }
Beispiel #15
0
        public ActionResult SSLOrder(string plans_ssl)
        {
            // get buyer
            var buyer = repository.GetUserById(sessionid.Value, subdomainid.Value);

            // check that user has all relevant fields filled up
            if (string.IsNullOrEmpty(buyer.firstName) ||
                string.IsNullOrEmpty(buyer.lastName) ||
                string.IsNullOrEmpty(buyer.organisation1.name) ||
                string.IsNullOrEmpty(buyer.organisation1.address) ||
                !buyer.organisation1.city.HasValue ||
                string.IsNullOrEmpty(buyer.organisation1.state) ||
                string.IsNullOrEmpty(buyer.organisation1.postcode) ||
                !buyer.organisation1.country.HasValue ||
                string.IsNullOrEmpty(buyer.organisation1.phone) ||
                string.IsNullOrEmpty(buyer.email))
            {
                return(Json("Please ensure that your personal & organisation details are complete".ToJsonFail()));
            }

            // get clear pixels domain
            var clearpixeldomain = repository.GetSubDomains().Single(x => x.name == "clearpixels");

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

            var ordernumber = repository.GetNewOrderNumber(clearpixeldomain.id, TransactionType.INVOICE);

            transaction.CreateTransaction(ordernumber, DateTime.UtcNow, "", CurrencyHelper.GetCurrencies().Where(x => x.code == "USD").Single().id);
            transaction.UpdateOrderStatus(OrderStatus.SENT);

            var variant = repository.GetProductVariant(plans_ssl, clearpixeldomain.id, null);

            var orderitem = new orderItem()
            {
                description = variant.product.title,
                variantid   = variant.id,
                unitPrice   = variant.product.sellingPrice,
                tax         = variant.product.tax,
                quantity    = 1
            };

            transaction.AddOrderItem(orderitem, null);

            // update order total
            transaction.UpdateTotal();
            transaction.SaveNewTransaction();

            // send email to seller
            Syslog.Write(string.Format("{0} bought by subdomainid {1}", plans_ssl, subdomainid.Value));

            // handle payment
            var uniqueid = string.Format("{0}:{1}", accountSubdomainName, plans_ssl);
            var pworker  = new PaypalWorker(uniqueid,
                                            transaction,
                                            repository,
                                            clearpixeldomain.GetPaypalID(),
                                            transaction.GetCurrency().id,
                                            accountHostname.ToDomainUrl("/dashboard/account/SSLProcess?d=" + plans_ssl));

            var redirecturl = pworker.GetPaymentUrl();

            return(Json(redirecturl.ToJsonOKData()));
        }
Beispiel #16
0
        private void SaveEbayOrders(OrderTypeCollection collection)
        {
            using (var repository = new TradelrRepository())
            {
                foreach (OrderType entry in collection)
                {
                    Transaction transaction;
                    // check if order already exists
                    var existingEbayOrder = repository.GetSubDomain(sd.id).ebay_orders.SingleOrDefault(x => x.orderid == entry.OrderID);

                    if (existingEbayOrder != null)
                    {
                        var order = existingEbayOrder.orders.Single();
                        transaction = new Transaction(order, repository, seller.id);

                        // update order status
                        existingEbayOrder.status = entry.OrderStatus.ToString();
                    }
                    else
                    {
                        // check if user already exists
                        var buyer = repository.GetUserByEbayID(entry.BuyerUserID);

                        if (buyer == null)
                        {
                            // get receiver and add to contact db
                            var userService = new UserService(token);

                            // get by itemid as invalid request seems to be returned when get by userid
                            var ebaybuyer = userService.GetUser(entry.BuyerUserID);

                            // we assume that same buyer for all transactions so we get the first email address
                            var buyeremail = entry.TransactionArray.ItemAt(0).Buyer.Email;

                            buyer = SaveEbayBuyer(ebaybuyer, buyeremail);
                        }

                        // add a shipping and billing address
                        if (entry.ShippingAddress != null)
                        {
                            var buyername = Utility.SplitFullName(entry.ShippingAddress.Name);
                            var handler   = new AddressHandler(buyer.organisation1, repository);
                            handler.SetShippingAndBillingAddresses(buyername[0],
                                                                   buyername[1],
                                                                   entry.ShippingAddress.CompanyName ?? "",
                                                                   entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2,
                                                                   entry.ShippingAddress.CityName,
                                                                   null,
                                                                   entry.ShippingAddress.PostalCode,
                                                                   entry.ShippingAddress.Phone,
                                                                   entry.ShippingAddress.Country.ToString().ToCountry().id,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   buyername[0],
                                                                   buyername[1],
                                                                   entry.ShippingAddress.CompanyName ?? "",
                                                                   entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2,
                                                                   entry.ShippingAddress.CityName,
                                                                   null,
                                                                   entry.ShippingAddress.PostalCode,
                                                                   entry.ShippingAddress.Phone,
                                                                   entry.ShippingAddress.Country.ToString().ToCountry().id,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   entry.ShippingAddress.StateOrProvince,
                                                                   true);
                        }

                        // add normal order
                        transaction = new Transaction(sd, buyer, TransactionType.INVOICE, repository, seller.id);

                        transaction.CreateTransaction(repository.GetNewOrderNumber(sd.id, TransactionType.INVOICE),
                                                      entry.CreatedTime, "",
                                                      entry.AmountPaid.currencyID.ToString().ToCurrency().id);

                        // mark as sent
                        var tradelr_orderstatus = GetOrderStatus(entry.OrderStatus);
                        transaction.UpdateOrderStatus(tradelr_orderstatus);

                        // add ebay specific order information
                        var newEbayOrder = new ebay_order();
                        newEbayOrder.orderid     = entry.OrderID;
                        newEbayOrder.status      = entry.OrderStatus.ToString();
                        newEbayOrder.created     = entry.CreatedTime;
                        newEbayOrder.subdomainid = sd.id;
                        transaction.AddEbayOrderInformation(newEbayOrder);

                        foreach (eBay.Service.Core.Soap.TransactionType trans in entry.TransactionArray)
                        {
                            var ebay_itemid = trans.Item.ItemID;

                            // get product details
                            var itemservice = new ItemService(token);
                            var item        = itemservice.GetItem(ebay_itemid);

                            // add new product if necessary
                            var existingproduct = repository.GetProducts(sd.id).SingleOrDefault(x => x.ebayID.HasValue && x.ebay_product.ebayid == ebay_itemid);
                            if (existingproduct == null)
                            {
                                // add new product  (triggered when synchronisation is carried out the first time)
                                var newproduct = new Listing();
                                newproduct.Populate(item);
                                var importer = new ProductImport();
                                var pinfo    = importer.ImportEbay(newproduct, sd.id);

                                repository.AddProduct(pinfo, sd.id);
                                existingproduct = pinfo.p;
                            }
                            else
                            {
                                // if existing product is completed then we need to relist
                                if (entry.OrderStatus == OrderStatusCodeType.Completed ||
                                    entry.OrderStatus == OrderStatusCodeType.Shipped)
                                {
                                    // see if product listing is still active
                                    if (item.SellingStatus.ListingStatus == ListingStatusCodeType.Completed ||
                                        item.SellingStatus.ListingStatus == ListingStatusCodeType.Ended)
                                    {
                                        // set status to inactive
                                        existingproduct.ebay_product.isActive = false;

                                        // check if we should autorelist
                                        if (existingproduct.ebay_product.autorelist)
                                        {
                                            // check that product has enough stock
                                            if (existingproduct.HasStock(existingproduct.ebay_product.quantity))
                                            {
                                                var exporter =
                                                    new EbayExporter(
                                                        existingproduct.ebay_product.siteid.ToEnum <SiteCodeType>(),
                                                        sd.ToHostName(),
                                                        token,
                                                        sd);

                                                exporter.BuildItem(existingproduct.ebay_product);
                                            }
                                        }
                                    }
                                }
                            }

                            // add tradelr order item
                            var orderItem = new orderItem
                            {
                                description = item.Title,
                                variantid   = existingproduct.product_variants[0].id,
                                unitPrice   = (decimal)trans.TransactionPrice.Value,
                                quantity    = trans.QuantityPurchased
                            };

                            if (trans.Taxes != null)
                            {
                                orderItem.tax =
                                    (decimal)(trans.Taxes.TotalTaxAmount.Value / trans.TransactionPrice.Value);
                            }

                            transaction.AddOrderItem(orderItem, null);

                            // update inventory
                            transaction.UpdateInventoryItem(orderItem, trans.QuantityPurchased);

                            // add ebay order item
                            var ebayorderitem = new ebay_orderitem();
                            ebayorderitem.lineid = trans.OrderLineItemID;
                            newEbayOrder.ebay_orderitems.Add(ebayorderitem);
                        }

                        // update shipping
                        transaction.UpdateShippingCost(entry.ShippingServiceSelected.ShippingServiceCost.Value.ToString());
                        transaction.UpdateShippingMethod(entry.ShippingServiceSelected.ShippingService);

                        // update tax : ebay tax is the shipping tax which applies to the entire order total
                        // may or may not include shipping cost
                        if (entry.ShippingDetails.SalesTax != null)
                        {
                            transaction.UpdateOrderTax((decimal)entry.ShippingDetails.SalesTax.SalesTaxPercent,
                                                       entry.ShippingDetails.SalesTax.ShippingIncludedInTax);
                        }


                        transaction.UpdateTotal();
                        transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE
                    }

                    // the following applies to both new and existing order
                    var existingPayment = transaction.GetPayments().SingleOrDefault(x => x.reference == entry.OrderID);
                    if (existingPayment != null)
                    {
                        var newstatus = GetPaymentStatus(entry.CheckoutStatus.Status);
                        if (existingPayment.status != newstatus.ToString())
                        {
                            transaction.UpdatePaymentStatus(existingPayment, newstatus);
                        }
                    }
                    else
                    {
                        // if payment has been made then add payment
                        if (entry.CheckoutStatus.Status == CompleteStatusCodeType.Complete)
                        {
                            var p = new DBML.payment();
                            p.status     = GetPaymentStatus(entry.CheckoutStatus.Status).ToString();
                            p.method     = entry.CheckoutStatus.PaymentMethod.ToString();
                            p.created    = entry.CheckoutStatus.LastModifiedTime;
                            p.notes      = entry.BuyerCheckoutMessage;
                            p.paidAmount = (decimal)entry.AmountPaid.Value;
                            p.reference  = entry.OrderID;

                            transaction.AddPayment(p, false);
                        }
                    }

                    // if there is a shipped date, mark as ship if not already done so
                    if (transaction.GetOrderStatus() != OrderStatus.SHIPPED &&
                        entry.ShippedTimeSpecified)
                    {
                        transaction.UpdateOrderStatus(OrderStatus.SHIPPED);

                        if (entry.ShippingDetails.ShipmentTrackingDetails.Count != 0)
                        {
                            foreach (ShipmentTrackingDetailsType trackentry in entry.ShippingDetails.ShipmentTrackingDetails)
                            {
                                var comment = string.Format(OrderComment.ORDER_SHIP_STANDARD,
                                                            trackentry.ShippingCarrierUsed,
                                                            trackentry.ShipmentTrackingNumber);
                                transaction.AddComment(comment);
                            }
                        }
                        else
                        {
                            transaction.AddComment(OrderComment.ORDER_SHIP, created: entry.ShippedTime);
                        }
                    }
                    repository.Save();  // save per order
                }
            }
        }
Beispiel #17
0
        public ActionResult DomainOrder(bool id_theft, string plans, string domain_name, string domain_ext)
        {
            // check that domain extension is supported
            if (!SupportedTLD.Extensions.Contains(domain_ext))
            {
                throw new NotImplementedException();
            }

            // get buyer
            var buyer = repository.GetUserById(sessionid.Value, subdomainid.Value);

            // check that user has all relevant fields filled up
            if (string.IsNullOrEmpty(buyer.firstName) ||
                string.IsNullOrEmpty(buyer.lastName) ||
                string.IsNullOrEmpty(buyer.organisation1.name) ||
                string.IsNullOrEmpty(buyer.organisation1.address) ||
                !buyer.organisation1.city.HasValue ||
                string.IsNullOrEmpty(buyer.organisation1.state) ||
                string.IsNullOrEmpty(buyer.organisation1.postcode) ||
                !buyer.organisation1.country.HasValue ||
                string.IsNullOrEmpty(buyer.organisation1.phone) ||
                string.IsNullOrEmpty(buyer.email))
            {
                return(Json("Please ensure that your personal & organisation details are complete".ToJsonFail()));
            }

            // get clear pixels domain
            var clearpixeldomain = repository.GetSubDomains().Single(x => x.name == "clearpixels");

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

            var ordernumber = repository.GetNewOrderNumber(clearpixeldomain.id, TransactionType.INVOICE);

            transaction.CreateTransaction(ordernumber, DateTime.UtcNow, "", CurrencyHelper.GetCurrencies().Single(x => x.code == "USD").id);
            transaction.UpdateOrderStatus(OrderStatus.SENT);

            // define id_theft order item
            var idtheft_variant   = repository.GetProductVariant("id_theft", clearpixeldomain.id, null);
            var idtheft_orderitem = new orderItem()
            {
                description = idtheft_variant.product.title,
                variantid   = idtheft_variant.id,
                unitPrice   = idtheft_variant.product.sellingPrice,
                tax         = idtheft_variant.product.tax
            };
            int             numberOfYears;
            product_variant variant;

            switch (plans)
            {
            case "one_year":
                variant = repository.GetProductVariant("one_year", clearpixeldomain.id, null);
                if (variant == null)
                {
                    throw new NotImplementedException();
                }
                numberOfYears = 1;
                break;

            case "two_year":
                variant = repository.GetProductVariant("two_year", clearpixeldomain.id, null);
                if (variant == null)
                {
                    throw new NotImplementedException();
                }
                numberOfYears = 2;
                break;

            case "five_year":
                variant = repository.GetProductVariant("five_year", clearpixeldomain.id, null);
                if (variant == null)
                {
                    throw new NotImplementedException();
                }
                numberOfYears = 5;
                break;

            case "ten_year":
                variant = repository.GetProductVariant("ten_year", clearpixeldomain.id, null);
                if (variant == null)
                {
                    throw new NotImplementedException();
                }
                numberOfYears = 10;
                break;

            default:
                throw new NotImplementedException();
            }

            var orderitem = new orderItem()
            {
                description = string.Format("{0}{1} {2}", domain_name, domain_ext, variant.product.title),
                variantid   = variant.id,
                unitPrice   = variant.product.sellingPrice,
                tax         = variant.product.tax,
                quantity    = numberOfYears
            };

            transaction.AddOrderItem(orderitem, null);

            if (id_theft)
            {
                idtheft_orderitem.quantity = numberOfYears;
                transaction.AddOrderItem(idtheft_orderitem, null);
            }

            // update order total
            transaction.UpdateTotal();
            transaction.SaveNewTransaction();

            // send email to seller
            Syslog.Write(string.Format("{0}{1} bought by subdomainid {2}", domain_name, domain_ext, subdomainid.Value));

            // handle payment
            var uniqueid = string.Format("{0}{1}", domain_name, domain_ext);
            var pworker  = new PaypalWorker(uniqueid,
                                            transaction,
                                            repository,
                                            clearpixeldomain.GetPaypalID(),
                                            transaction.GetCurrency().id,
                                            accountHostname.ToDomainUrl("/dashboard/account/DomainProcess?d=" + uniqueid));


            var redirecturl = pworker.GetPaymentUrl();

            return(Json(redirecturl.ToJsonOKData()));
        }
Beispiel #18
0
        public void ShouldCheckTxInputExisitsAndHasCorrectAmount()
        {
            (bool, string)txResponse = _transaction.CreateTransaction(_wallet, recipientAddress, amountToSend);

            Assert.Equal(_transaction.Input.Amount, _wallet.Balance);
        }
Beispiel #19
0
 public void CreateTransaction(int userId, string typeOfTransaction)
 {
     Transaction.CreateTransaction(userId, typeOfTransaction);
 }