public ServiceResult Delete(FinanceAccountTransaction s) { if (s == null || string.IsNullOrWhiteSpace(s.UUID)) { return(ServiceResponse.Error("Invalid account was sent.")); } FinanceAccountTransactionsManager financeManager = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); return(financeManager.Delete(s)); }
public ServiceResult Delete(FinanceAccountTransaction s) { if (s == null || string.IsNullOrWhiteSpace(s.UUID)) { return(ServiceResponse.Error("Invalid account was sent.")); } FinanceAccountTransactionsManager financeManager = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); return(financeManager.Delete(s)); }
public ServiceResult AddFinanceAccountTransaction(FinanceAccountTransaction s) { if (s == null || string.IsNullOrWhiteSpace(s.Name)) { return(ServiceResponse.Error("Invalid FinanceAccountTransaction sent to server.")); } string authToken = Request.Headers?.Authorization?.Parameter; UserSession us = SessionManager.GetSession(authToken); if (us == null) { return(ServiceResponse.Error("You must be logged in to access this function.")); } if (string.IsNullOrWhiteSpace(us.UserData)) { return(ServiceResponse.Error("Couldn't retrieve user data.")); } if (CurrentUser == null) { return(ServiceResponse.Error("You must be logged in to access this function.")); } if (string.IsNullOrWhiteSpace(s.AccountUUID) || s.AccountUUID == SystemFlag.Default.Account) { s.AccountUUID = CurrentUser.AccountUUID; } if (string.IsNullOrWhiteSpace(s.CreatedBy)) { s.CreatedBy = CurrentUser.UUID; } if (s.DateCreated == DateTime.MinValue) { s.DateCreated = DateTime.UtcNow; } if (string.IsNullOrWhiteSpace(s.Image)) { s.Image = "/Content/Default/Images/FinanceAccountTransaction/default.png"; } FinanceAccountTransactionsManager financeManager = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); return(financeManager.Insert(s, false)); }
public ServiceResult Update(FinanceAccountTransaction fat) { if (fat == null) { return(ServiceResponse.Error("Invalid FinanceAccountTransaction sent to server.")); } FinanceAccountTransactionsManager financeManager = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); var res = financeManager.Get(fat.UUID); if (res.Code != 200) { return(res); } var dbS = (FinanceAccountTransaction)res.Result; if (dbS.DateCreated == DateTime.MinValue) { dbS.DateCreated = DateTime.UtcNow; } dbS.Name = fat.Name; dbS.Image = fat.Image; dbS.Deleted = fat.Deleted; dbS.Status = fat.Status; dbS.SortOrder = fat.SortOrder; //FinanceAccountUUID //PayToAccountUUID // PayFromAccountUUID // CreationDate // CustomerIp //LastPaymentStatusCheck // OrderUUID // Amount // TransactionType // TransactionDate // PaymentTypeUUID // AmountTransferred // SelectedPaymentTypeSymbol //SelectedPaymentTypeTotal // UserUUID // CustomerEmail // CurrencyUUID return(financeManager.Update(dbS)); }
public ServiceResult Update(FinanceAccountTransaction fat) { if (fat == null) { return(ServiceResponse.Error("Invalid FinanceAccountTransaction sent to server.")); } FinanceAccountTransactionsManager financeManager = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); var dbS = (FinanceAccountTransaction)financeManager.GetBy(fat.UUID); if (dbS == null) { return(ServiceResponse.Error("FinanceAccountTransaction was not found.")); } if (dbS.DateCreated == DateTime.MinValue) { dbS.DateCreated = DateTime.UtcNow; } dbS.Name = fat.Name; dbS.Image = fat.Image; dbS.Deleted = fat.Deleted; dbS.Status = fat.Status; dbS.SortOrder = fat.SortOrder; //FinanceAccountUUID //PayToAccountUUID // PayFromAccountUUID // CreationDate // CustomerIp //LastPaymentStatusCheck // OrderUUID // Amount // TransactionType // TransactionDate // PaymentTypeUUID // AmountTransferred // SelectedPaymentTypeSymbol //SelectedPaymentTypeTotal // UserUUID // CustomerEmail // CurrencyUUID return(financeManager.Update(dbS)); }
public ServiceResult DeleteFinanceAccountTransactionBy(string uuid) { if (string.IsNullOrWhiteSpace(uuid)) { return(ServiceResponse.Error("Invalid id.")); } FinanceAccountTransactionsManager fm = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); FinanceAccountTransaction c = (FinanceAccountTransaction)fm.GetBy(uuid); if (c == null) { return(ServiceResponse.Error("Invalid uuid")); } return(fm.Delete(c)); }
public ServiceResult DeleteFinanceAccountTransactionBy(string uuid) { if (string.IsNullOrWhiteSpace(uuid)) { return(ServiceResponse.Error("Invalid id.")); } FinanceAccountTransactionsManager fm = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); var res = fm.Get(uuid); if (res.Code != 200) { return(res); } FinanceAccountTransaction c = (FinanceAccountTransaction)res.Result; return(fm.Delete(c)); }
public ServiceResult GetFinanceAccountTransactionByName(string name) { if (string.IsNullOrWhiteSpace(name)) { return(ServiceResponse.Error("You must provide a name for the strain.")); } FinanceAccountTransactionsManager financeManager = new FinanceAccountTransactionsManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); FinanceAccountTransaction s = (FinanceAccountTransaction)financeManager.Get(name); if (s == null) { return(ServiceResponse.Error("FinanceAccountTransaction could not be located for the name " + name)); } return(ServiceResponse.OK("", s)); }
/// <summary> /// This was created for use in the bulk process.. /// /// </summary> /// <param name="p"></param> /// <param name="checkName">This will check the products by name to see if they exist already. If it does an error message will be returned.</param> /// <returns></returns> public ServiceResult Insert(INode n, bool validateFirst = true) { if (!this.DataAccessAuthorized(n, "POST", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } n.Initialize(this._requestingUser.UUID, this._requestingUser.AccountUUID, this._requestingUser.RoleWeight); var p = (FinanceAccountTransaction)n; if (validateFirst) { FinanceAccountTransaction dbU = (FinanceAccountTransaction)Get(p.Name); if (dbU != null) { return(ServiceResponse.Error("FinanceAccountTransaction already exists.")); } if (string.IsNullOrWhiteSpace(p.CreatedBy)) { return(ServiceResponse.Error("You must assign who the product was created by.")); } if (string.IsNullOrWhiteSpace(p.AccountUUID)) { return(ServiceResponse.Error("The account id is empty.")); } } using (var context = new TreeMonDbContext(this._connectionKey)) { if (context.Insert <FinanceAccountTransaction>(p)) { return(ServiceResponse.OK("", p)); } } return(ServiceResponse.Error("An error occurred inserting product " + p.Name)); }
//pass cart by ref because it persists in the session, so we want to update the //cart in case something happens and we need to go back and to update/insert. //userId is whom the order is for,this is using current session userid. // If an admin created the order we'll have to create a //new order function CreateOrderFor(userId ) // public ServiceResult ProcessPayment(CartView cart, string ipAddress) { if (cart == null) { return(ServiceResponse.Error("Invalid check out form.")); } if (string.IsNullOrEmpty(cart.FinanceAccountUUID)) { return(ServiceResponse.Error("You must select a payment method.")); } User user = this.GetUser(this.SessionKey); Order order = new Order(); FinanceAccount financeAccount = new FinanceAccount(); try { using (var transactionScope = new TransactionScope()) using (var context = new TreeMonDbContext(this._connectionKey)) { if (user == null) //use form.email to see if there is already an account. if not create one. { user = context.GetAll <User>().FirstOrDefault(w => w.UUID == cart.UserUUID); } if (user == null) { return(ServiceResponse.Error("You must login or create an account.")); } financeAccount = context.GetAll <FinanceAccount>().FirstOrDefault(w => w.UUID == cart.FinanceAccountUUID); if (financeAccount == null) { return(ServiceResponse.Error("You must select a payment method.")); } #region old btc code //If btc I recall reading optimally you want a new btc address for each transaction, the send the btc to your main address after full payment is made. //Get the account the currency is going to be paid to. // FinanceAccount payToAcct = new FinanceAccount(); // form.PayTypeUUID get the finance account for paytype. so if payment type is btc, get the default or active account for the btc. // string accountNumber = ""; // if (PayType.Symbol.EqualsIgnoreCase("BTC" || PayType.Symbol.EqualsIgnoreCase("BTCT") // { // payToAcct = CreateNewBtcAccount(); // if (payToAcct == null) // { // Message = "Could not create an account for Payment type:" + paymentTypeId.ToString() + " is test:" + Globals.UsePaymentTestnet.ToString(); // LogQueries.InsertError(Message, className, MethodInfo.GetCurrentMethod().Name); // Debug.Assert(false, Message); // return false; // } // accountNumber = payToAcct.AccountNumber; // AccountImage = payToAcct.ImageUrl; //Market.GetQrCodePath(accountNumber, PayType.Symbol), true); // } #endregion #region Affiliate process. //todo move to affiliate manager. Also this uses the parent id. we may want to use another refernce since we have accounts now that can establish a heirarchy ////If the current user has a parent id (ie under a user) then get that users affiliate account info so they ////get credit for the sale. //int affiliateId = -1; //string type = string.Empty; //if (currentUser.ParentId > 0) //{ // Omni.Models.Users.User parentUser = new UserManager().Get(currentUser.ParentId); // if (parentUser != null && parentUser.IsBanned == false && parentUser.IsApproved == true) // { // Affiliate aff = UserQueries.GetAll<Affiliate>().FirstOrDefault(af => af.UserId == currentUser.ParentId); // if (aff != null) // { // affiliateId = aff.Id; // type = "affiliate"; // } // } //} #endregion List <ShoppingCartItem> cartItems = context.GetAll <ShoppingCartItem>().Where(w => w.ShoppingCartUUID == cart.UUID).ToList(); order = context.GetAll <Order>().OrderByDescending(ob => ob.DateCreated) .FirstOrDefault(w => w.UserUUID == cart.UserUUID && w.CartUUID == cart.UUID); Debug.Assert(false, "TODO verify not getting duplicate rules."); List <PriceRuleLog> priceRules = cart.PriceRules; //todo get mandatory price rules // todo implement shipping/delivery and make sure it's tracked properly. cart.ShippingMethodUUID //List<PriceRule> mandatoryRules = context.GetAll<PriceRule>() // .Where( w => w.AccountUUID == user.AccountUUID && // w.Mandatory == true && w.Deleted == false && // priceRules.Any( a => a.PriceRuleUUID != w.UUID) // ).ToList(); //priceRules.AddRange(mandatoryRules); decimal subTotal = this.GetSubtotal(cartItems); //todo validate the price rules (only one coupon, expiration date hasn't exceeded, max usage hasn't exceeded..) decimal total = MathHelper.CalcAdjustment(subTotal, ref priceRules); if (order == null) { order = new Order() { CartUUID = cart.UUID, AddedBy = user.UUID, Status = StoreFlag.OrderStatus.Recieved, PayStatus = LedgerFlag.Status.PendingIncome, UserUUID = user.UUID, SubTotal = subTotal, Total = total, CurrencyUUID = financeAccount.CurrencyUUID, DateCreated = DateTime.UtcNow, AccountUUID = user.AccountUUID, Active = true, FinancAccountUUID = financeAccount.UUID }; context.Insert <Order>(order); } if (priceRules.Count > 0) { priceRules.ForEach(x => { x.TrackingId = order.UUID; x.TrackingType = "Order"; if (!context.Insert <PriceRuleLog>(x)) { this._logger.InsertError("Failed to insert PriceRuleLog", "StoreManager", "ProcessPayment cart:" + cart.UUID + " PriceRuleLog:" + x.UUID); } }); } #region todo Currency conversion. May not be needed or move to somewhere else. //// get payment type. then use symbol for conversion ////paymentTypeId //PayType = StoreQueries.GetPaymentTypes().FirstOrDefault(pt => pt.Id == paymentTypeId); decimal orderTotalConverted = order.Total; //PayTypeTotal = TODO => Market.ConvertCurrencyAmmount(Globals.CurrencySymbol, PayType.Symbol, Cart.Total); decimal orderSubTotalConverted = 0; //PayTypeSubTotal if (order.Total == order.SubTotal) { orderSubTotalConverted = orderTotalConverted; } else { orderSubTotalConverted = order.SubTotal; //TODO => // Market.ConvertCurrencyAmmount(Globals.CurrencySymbol, PayType.Symbol, Cart.SubTotal); } #endregion //Clear order items and refresh with members selected items. DynamicParameters parameters = new DynamicParameters(); parameters.Add("@ORDERUUID", order.UUID); context.Delete <OrderItem>("WHERE OrderUUID=@ORDERUUID", parameters); foreach (ShoppingCartItem item in cartItems) { InventoryItem p = context.GetAll <InventoryItem>().FirstOrDefault(w => w.UUID == item.ItemUUID); if (p == null) { Debug.Assert(false, "PRODUCT NOT FOUND"); _logger.InsertError("Product not found:" + item.UUID + " Name:" + item.Name, "StoreManager", "ProcessPayment"); continue; } OrderItem orderItem = new OrderItem() { OrderUUID = order.UUID, UserUUID = user.UUID, Quantity = item.Quantity, Price = item.Price, SKU = item.SKU, Status = LedgerFlag.Status.PendingIncome, // PaymentStatusUUID RoleWeight = item.RoleWeight, RoleOperation = item.RoleOperation, CreatedBy = item.UserUUID, DateCreated = DateTime.UtcNow, AccountUUID = user == null ? "" : user.AccountUUID, Name = item.Name, ProductUUID = item.ItemUUID, ProductType = item.ItemType, Image = item.Image, UnitsInProduct = p.UnitsInProduct, UnitsRemaining = p.UnitsInProduct * item.Quantity, UnitType = p.UnitType, IsVirtual = p.Virtual, AccessGranted = false, AccessExpires = DateTime.UtcNow.AddDays(120) //todo make configurable //TODO AffiliateUUID }; if (!context.Insert <OrderItem>(orderItem)) { this._logger.InsertError("Failed to insert OrderItem", "StoreManager", "ProcessPayment cart:" + cart.UUID + " PriceRuleLog:" + orderItem.UUID); } } Currency currency = context.GetAll <Currency>().FirstOrDefault(w => w.UUID == financeAccount.CurrencyUUID); //Add an initial payment record so we know who owes what FinanceAccountTransaction payment = new FinanceAccountTransaction() { AccountUUID = user.AccountUUID, AccountEmail = financeAccount.Email, DateCreated = DateTime.UtcNow, Image = financeAccount.Image, CurrencyUUID = financeAccount.CurrencyUUID, CustomerIp = ipAddress, CreationDate = DateTime.Now, LastPaymentStatusCheck = DateTime.UtcNow, OrderUUID = order.UUID, Balance = orderTotalConverted, AmountTransferred = 0, TransactionDate = DateTime.UtcNow, TransactionType = LedgerFlag.TransactionTypes.Credit, Status = LedgerFlag.Status.PendingIncome, SelectedPaymentTypeTotal = orderTotalConverted, UserUUID = user.UUID, // PayFromAccountUUID = todo this is the customers account id. won't need it for now. we could also use it to set up accounts where users // can order and be billed later. FinanceAccountUUID = financeAccount.UUID, PayToAccountUUID = financeAccount.AccountNumber, //todo this should be the store account", PaymentTypeUUID = cart.PaymentGateway, SelectedPaymentTypeSymbol = currency?.Symbol //yes I used a null check operator here just in case. It's not critical piece of info and we don't want to stop operations because of it. // = affiliateId, }; if (!context.Insert <FinanceAccountTransaction>(payment)) { this._logger.InsertError("Failed to insert FinanceAccountTransaction", "StoreManager", "ProcessPayment cart:" + cart.UUID + " PriceRuleLog:" + payment.UUID); } //order has been placed so remove the cart and contents DynamicParameters cartParams = new DynamicParameters(); parameters.Add("@UUID", cart.UUID); context.Delete <ShoppingCart>("WHERE UUID=@UUID", cartParams); DynamicParameters cartItemParams = new DynamicParameters(); parameters.Add("@CARTUUID", cart.UUID); context.Delete <ShoppingCartItem>("WHERE ShoppingCartUUID=@CARTUUID", cartItemParams); transactionScope.Complete(); } } catch (Exception ex) { Debug.Assert(false, ex.Message); _logger.InsertError(ex.Message, "StoreManager", "ProcessPayment"); return(ServiceResponse.Error("Failed to process payment.")); } //todo get app setting if pos system don't show this message, return(SendEmail(cart, order, financeAccount, user.Email, StoreFlag.OrderStatus.Recieved)); }
private void ProcessPayPalPurchase(PayPalResponse ipnResponse) { if (ipnResponse == null) { return; } if (ipnResponse.payment_status?.ToLower() != "completed") { return; } try { using (var transactionScope = new TransactionScope()) using (var context = new GreenWerxDbContext(_dbConnectionKey)) { Order o = context.GetAll <Order>()?.FirstOrDefault(w => w.CartUUID == ipnResponse.custom); if (o == null) { // get order by shoppingCartUUID == ipnResponse.custom Debug.Assert(false, "ORDER NOT FOUND"); _logger.InsertError("ORDER NOT FOUND custom value:" + ipnResponse.custom, "PaymentGateway", "ProcessPayPalPurchase"); return; } if (o.TransactionID == ipnResponse.txn_id) { // check that Txn_id has not been previously processed Debug.Assert(false, "TRANSACTION ALREADY PROCESSED"); _logger.InsertError("TRANSACTION ALREADY PROCESSED:" + ipnResponse.txn_id, "PaymentGateway", "ProcessPayPalPurchase"); return; } if (o.Total > ipnResponse.mc_gross) { // Debug.Assert(false, "UNDERPAYMENT RECIEVED"); o.PayStatus = LedgerFlag.Status.PaymentPartialRecieved; _logger.InsertInfo("UNDERPAYMENT RECIEVED order uuid:" + o.UUID, "PaymentGateway", "ProcessPayPalPurchase"); // return; } if (o.Total < ipnResponse.mc_gross) { o.PayStatus = LedgerFlag.Status.OverPaymentReceived; //Debug.Assert(false, "OVERPAYMENT RECIEVED"); _logger.InsertInfo("OVERPAYMENT RECIEVED order uuid:" + o.UUID, "PaymentGateway", "ProcessPayPalPurchase"); // return; } if (o.Total == ipnResponse.mc_gross) { o.PayStatus = LedgerFlag.Status.Paid; } FinanceAccount financeAccount = context.GetAll <FinanceAccount>()?.FirstOrDefault(w => w.UUID == o.FinancAccountUUID); if (financeAccount == null) { Debug.Assert(false, "Unable to find finance account."); _logger.InsertInfo("Unable to find finance account.:" + o.FinancAccountUUID, "PaymentGateway", "ProcessPayPalPurchase"); return; } var app = new AppManager(_dbConnectionKey, "web", ""); string secret = app.GetSetting("AppKey")?.Value; var email = Cipher.Crypt(secret, ipnResponse.receiver_email.ToLower(), true); if (financeAccount.Email != email) { // check that Receiver_email is your Primary PayPal email Debug.Assert(false, "Receiver_email doesn't match financeAccount Email"); _logger.InsertInfo("Receiver_email doesn't match financeAccount Email:" + email + ":" + financeAccount.Email, "PaymentGateway", "ProcessPayPalPurchase"); return; } Currency currency = context.GetAll <Currency>( )?.FirstOrDefault(w => w.UUID == o.CurrencyUUID); if (currency == null) { Debug.Assert(false, "Unable to find currency ."); _logger.InsertInfo("Unable to find currency .:" + o.CurrencyUUID, "PaymentGateway", "ProcessPayPalPurchase"); return; } if (!currency.Code.EqualsIgnoreCase(ipnResponse.mc_currency)) { // check that mc_gross/mc_currency = USD are correct Debug.Assert(false, "mc_currency doesn't match currency.Code"); _logger.InsertInfo("mc_currency doesn't match currency.Code:" + ipnResponse.mc_currency + ":" + currency.Code, "PaymentGateway", "ProcessPayPalPurchase"); return; } if (o.PayStatus == LedgerFlag.Status.Paid || o.PayStatus == LedgerFlag.Status.OverPaymentReceived) { List <OrderItem> orderItems = context.GetAll <OrderItem>()?.Where(w => w.OrderUUID == o.UUID).ToList(); foreach (OrderItem oi in orderItems) { oi.AccessGranted = true; oi.AccessExpires = DateTime.UtcNow.AddDays(120); //todo make configurable. context.Update <OrderItem>(oi); } } //update order status to paid or complete etc. FinanceAccountTransaction payment = new FinanceAccountTransaction() { AccountEmail = financeAccount.Email, DateCreated = DateTime.UtcNow, Image = financeAccount.Image, CurrencyUUID = financeAccount.CurrencyUUID, //CustomerIp = ipAddress, CreationDate = DateTime.Now, LastPaymentStatusCheck = DateTime.UtcNow, OrderUUID = o.UUID, Balance = o.Total - ipnResponse.mc_gross, AmountTransferred = 0, TransactionDate = DateTime.UtcNow, TransactionType = LedgerFlag.TransactionTypes.Credit, Status = LedgerFlag.Status.PendingIncome, SelectedPaymentTypeTotal = o.Total, UserUUID = o.UserUUID, // PayFromAccountUUID = todo this is the customers account id. won't need it for now. we could also use it to set up accounts where users // can order and be billed later. FinanceAccountUUID = financeAccount.UUID, PayToAccountUUID = financeAccount.AccountNumber, //todo this should be the store account", PaymentTypeUUID = "PayPal", SelectedPaymentTypeSymbol = currency?.Symbol // // = affiliateId, }; context.Insert <FinanceAccountTransaction>(payment); transactionScope.Complete(); } } catch (Exception ex) { Debug.Assert(false, ex.Message); _logger.InsertError(ex.Message, "PaymentGateway", "ProcessPayPalPurchase"); } }