public ServiceResult Delete(INode n, bool purge = false) { if (n == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(n, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var p = (Vendor)n; try { using (var context = new TreeMonDbContext(this._connectionKey)) { if (purge) { DynamicParameters parameters = new DynamicParameters(); parameters.Add("@VendorUUID", p.UUID); if (context.Delete <Vendor>("WHERE UUID=@VendorUUID", parameters) > 0) { DynamicParameters credParams = new DynamicParameters(); credParams.Add("@UUID", p.UUID); credParams.Add("@TYPE", "Vendor"); context.Delete <Credential>("WHERE RecipientUUID=@UUID AND RecipientType=@TYPE", credParams); return(ServiceResponse.OK()); } } else { p.Deleted = true; if (context.Update <Vendor>(p) > 0) { return(ServiceResponse.OK()); } } } return(ServiceResponse.Error("No records deleted.")); //SQLITE //this was the only way I could get it to delete a RolePermission without some stupid EF error. //object[] paramters = new object[] { rp.PermissionUUID , rp.RoleUUID ,rp.AccountUUID }; //context.Delete<RolePermission>("WHERE PermissionUUID=? AND RoleUUID=? AND AccountUUID=?", paramters); // context.Delete<RolePermission>(rp); } catch (Exception ex) { _logger.InsertError(ex.Message, "VendorManager", "DeleteVendor:" + p.UUID); Debug.Assert(false, ex.Message); return(ServiceResponse.Error("Exception occured while deleting this record.")); } }
public int Delete(LogEntry l) { using (var context = new TreeMonDbContext(_dbConnectionKey)) { return(context.Delete <LogEntry>(l)); } }
public ServiceResult Delete(INode n, bool purge = false) { ServiceResult res = ServiceResponse.OK(); if (n == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(n, "delete", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var s = (TMG.Attribute)n; using (var context = new TreeMonDbContext(this._connectionKey)) { if (context.Delete <TMG.Attribute>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } return(res); }
public ServiceResult Delete(INode n, bool purge = false) { if (n == null || string.IsNullOrWhiteSpace(n.UUID)) { return(ServiceResponse.Error("You must pass in a valid user.")); } var user = (User)n; try { if (!this.DataAccessAuthorized(user, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } User u = new User(); using (var context = new TreeMonDbContext(this._connectionKey)) { if (!purge) { u.Deleted = true; return(Update(u)); } context.Delete <User>(u); } } catch (Exception ex) { _logger.InsertError(ex.Message, "UserManager", "DeleteUser:" + user.UUID); Debug.Assert(false, ex.Message); return(ServiceResponse.Error(ex.Message)); } return(ServiceResponse.OK()); }
public ServiceResult Delete(INode n, bool purge = false) { if (n == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(n, "delete", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var s = (StatusMessage)n; using (var context = new TreeMonDbContext(this._connectionKey)) { if (purge) { if (context.Delete <StatusMessage>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } else { s.Deleted = false; if (context.Update <StatusMessage>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } } return(ServiceResponse.OK()); }
public int Delete(AnatomyTag s, bool purge = false) { if (s == null) { return(0); } if (!this.DataAccessAuthorized(s, "DELETE", false)) { return(0); } List <AnatomyTag> pms = new List <AnatomyTag>(); if (purge) { using (var context = new TreeMonDbContext(this._connectionKey)) { return(context.Delete <AnatomyTag>(s)); } } //get the AnatomyTag from the table with all the data so when its updated it still contains the same data. s = this.GetAnatomyTagBy(s.UUID); if (s == null) { return(0); } s.Deleted = true; using (var context = new TreeMonDbContext(this._connectionKey)) { return(context.Update <AnatomyTag>(s)); } }
/// <summary> /// 1. remove record in usersinaccounts AccountMember where AccountUUID and user id match /// 2. check user record and make sure the account id doesn't match. If it does erase the field. /// TBD may need other proccessing /// </summary> /// <param name="accountUUID"></param> /// <param name="userUUID"></param> /// <returns></returns> public ServiceResult RemoveUserFromAccount(string accountUUID, string userUUID) { if (string.IsNullOrWhiteSpace(accountUUID)) { return(ServiceResponse.Error("Invalid account id")); } if (string.IsNullOrWhiteSpace(userUUID)) { return(ServiceResponse.Error("Invalid user id")); } if (!IsUserInAccount(accountUUID, userUUID)) { return(ServiceResponse.OK()); } //if (!this.DataAccessAuthorized(a, "PATCH", false)) return ServiceResponse.Error("You are not authorized this action."); User u = null; try { using (var context = new TreeMonDbContext(this._connectionKey)) { u = context.GetAll <User>().FirstOrDefault(w => w.UUID == userUUID); if (u == null) { return(ServiceResponse.Error("Invalid user id")); } DynamicParameters parameters = new DynamicParameters(); parameters.Add("@AccountUUID", accountUUID); parameters.Add("@MEMBERID", userUUID); int res = context.Delete <AccountMember>("WHERE AccountUUID=@AccountUUID AND MemberUUID=@MEMBERID", parameters); //Remove the reference in the xref table //SQLITE SYNTAX // object[] parameters = new object[] { accountUUID, userUUID }; // int res = context.Delete<AccountMember>("WHERE AccountUUID=? AND MemberUUID=?", parameters); if (u.AccountUUID == accountUUID) { u.AccountUUID = ""; if (context.Update <User>(u) == 0) { return(ServiceResponse.Error("Failed to remove user " + u.Name)); } } } } catch (Exception ex) { _logger.InsertError(ex.Message, "AccountManager", "RemoveUserFromAccount:accountUUID:" + accountUUID + " userUUID" + userUUID); Debug.Assert(false, ex.Message); return(ServiceResponse.Error(ex.Message)); } return(ServiceResponse.OK(string.Format("User {0} removed from account.", u.Name))); }
public ServiceResult Delete(INode n, bool purge = false) { if (n == null) { return(ServiceResponse.Error("No account record sent.")); } if (n.UUID == this._requestingUser.AccountUUID) //todo check if any user has this as default account { return(ServiceResponse.Error("Cannot delete a default account. You must select another account as default before deleting this one.")); } if (!this.DataAccessAuthorized(n, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var account = (Account)n; using (var context = new TreeMonDbContext(this._connectionKey)) { Account a = context.GetAll <Account>().FirstOrDefault(w => w.UUID == account.UUID); if (!this.DataAccessAuthorized(a, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } if (!purge) { Account dbAcct = context.GetAll <Account>().FirstOrDefault(w => w.UUID == a.UUID); if (dbAcct == null) { return(ServiceResponse.Error("Account not found.")); } dbAcct.Deleted = true; return(Update(dbAcct)); } try { if (context.Delete <Account>(a) > 0) { return(ServiceResponse.OK()); } return(ServiceResponse.Error("No records deleted.")); } catch (Exception ex) { _logger.InsertError(ex.Message, "AccountManager", "DeleteAccount:" + account.UUID); Debug.Assert(false, ex.Message); return(ServiceResponse.Error(ex.Message)); } } }
/// <summary> /// Delete tokens for the specific deleted user /// </summary> /// <param name="userUUID"></param> /// <returns>true for successful delete</returns> public bool DeleteByUserId(string userUUID) { DynamicParameters parameters = new DynamicParameters(); parameters.Add("@USERID", userUUID); using (var context = new TreeMonDbContext(_connectionKey)) { return(context.Delete <UserSession>("WHERE UserUUID=@USERID", parameters) > 0 ? true : false); } }
/// <summary> /// Method to kill the provided token id. /// </summary> /// <param name="tokenId">true for successful delete</param> public bool DeleteSession(string tokenId) { DynamicParameters p = new DynamicParameters(); p.Add("@TOKEN", tokenId); using (var context = new TreeMonDbContext(_connectionKey)) { return(context.Delete <UserSession>("WHERE AuthToken=@TOKEN", p) > 0 ? true : false); } }
public ServiceResult Delete(INode n, bool purge = false) { ServiceResult res = ServiceResponse.OK(); if (n == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(n, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var p = (Product)n; try { DynamicParameters parameters = new DynamicParameters(); parameters.Add("@PRODUCTUUID", p.UUID); using (var context = new TreeMonDbContext(this._connectionKey)) { if (purge) { if (context.Delete <Product>("WHERE UUID=@PRODUCTUUID", parameters) == 0) { return(ServiceResponse.Error(p.Name + " failed to delete. ")); } } else { p.Deleted = true; if (context.Update <Product>(p) == 0) { return(ServiceResponse.Error(p.Name + " failed to delete. ")); } } } //SQLITE //this was the only way I could get it to delete a RolePermission without some stupid EF error. //object[] paramters = new object[] { rp.PermissionUUID , rp.RoleUUID ,rp.AccountUUID }; //context.Delete<RolePermission>("WHERE PermissionUUID=? AND RoleUUID=? AND AccountUUID=?", paramters); // context.Delete<RolePermission>(rp); } catch (Exception ex) { _logger.InsertError(ex.Message, "ProductManager", "DeleteProduct"); Debug.Assert(false, ex.Message); return(ServiceResponse.Error("Exception occured while deleting this record.")); } return(res); }
public ServiceResult DeleteCartItem(string cartItemUUID) { InventoryManager inventoryManager = new InventoryManager(this._connectionKey, _sessionKey); ShoppingCartItem cartItem = this.GetCartItem(cartItemUUID); if (cartItem == null) { return(ServiceResponse.Error("Item not found in cart.")); } InventoryItem item = (InventoryItem)inventoryManager.GetBy(cartItem.ItemUUID); if (item == null) { return(ServiceResponse.Error("Product wasn't found.")); } if (!item.Virtual) { item.Quantity += cartItem.Quantity; //add the item back to inventory. } User u = this.GetUser(_sessionKey); using (var transactionScope = new TransactionScope()) using (var dbContext = new TreeMonDbContext(this._connectionKey)) { try { if (dbContext.Delete <ShoppingCartItem>(cartItem) <= 0) { _logger.InsertError("Failed to delete shopping cart item. " + cartItem.UUID, "StoreManager", MethodInfo.GetCurrentMethod().Name); return(ServiceResponse.Error("Failed to delete shopping cart.")); } if (dbContext.Update <InventoryItem>(item) <= 0) { _logger.InsertError("Failed to update inventory. " + item.UUID, "StoreManager", MethodInfo.GetCurrentMethod().Name); return(ServiceResponse.Error("Failed to update inventory.")); } transactionScope.Complete(); // remainingStock = item.Quantity; } catch (Exception ex) { _logger.InsertError(ex.Message, "StoreManager", MethodInfo.GetCurrentMethod().Name); return(ServiceResponse.Error("Failed to delete item.")); } } return(ServiceResponse.OK()); }
public void TreeMonDbContext_Context_Delete() { TreeMonDbContext context = new TreeMonDbContext("MSSQL_TEST"); User u = TestHelper.GenerateTestUser("DELETE_ME"); Assert.IsTrue(context.Insert <User>(u), "failed to insert user for test"); u = context.Get <User>(u.Id); Assert.IsNotNull(u); Assert.AreEqual(u.Name, "DELETE_ME"); int res = context.Delete <User>(u); Assert.AreEqual(res, 1); Assert.IsNull(context.Get <User>(u.Id)); }
public ServiceResult Delete(INode n, bool purge = false) { if (n == null) { return(ServiceResponse.Error("Invalid Order data.")); } if (!this.DataAccessAuthorized(n, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var s = (Order)n; List <Order> pms = new List <Order>(); using (var context = new TreeMonDbContext(this._connectionKey)) { if (purge) { if (context.Delete <Order>(s) > 0) { return(ServiceResponse.OK()); } else { return(ServiceResponse.Error("Failed to delete the order.")); } } //get the Order from the table with all the data so when its updated it still contains the same data. s = (Order)this.GetBy(s.UUID); if (s == null) { return(ServiceResponse.Error("Could not find order.")); } s.Deleted = true; if (context.Update <Order>(s) > 0) { return(ServiceResponse.OK()); } else { return(ServiceResponse.Error("Failed to delete the order.")); } } }
///This removes the user from all accounts public ServiceResult RemoveUserFromAllAccounts(string userUUID) { ServiceResult res = ServiceResponse.OK(); User u = null; try { using (var context = new TreeMonDbContext(this._connectionKey)) { //Make sure correct userid is passed in. u = context.GetAll <User>().FirstOrDefault(w => w.UUID == userUUID); if (u == null) { return(ServiceResponse.Error("Invalid user id.")); } if (!this.DataAccessAuthorized(u, "PATCH", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } DynamicParameters parameters = new DynamicParameters(); parameters.Add("@MEMBERID", userUUID); context.Delete <AccountMember>("WHERE MemberUUID=@MEMBERID", parameters); //SQLITE //Remove the reference in the xref table //object[] parameters = new object[] { userUUID }; //context.Delete<AccountMember>("WHERE MemberUUID=?", parameters); //now make sure the primary account in the user table is emptied. u.AccountUUID = ""; if (context.Update <User>(u) == 0) { return(ServiceResponse.Error(u.Name + " failed to update. ")); } } } catch (Exception ex) { _logger.InsertError(ex.Message, "AccountManager", "RemoveUserFromAllAccounts:userUUID:" + userUUID); Debug.Assert(false, ex.Message); return(ServiceResponse.Error("Exception occured while deleting this record.")); } return(res); }
public void TreeMonDbContext_Context_Delete_Where() { TreeMonDbContext context = new TreeMonDbContext("MSSQL_TEST"); User u = TestHelper.GenerateTestUser("DELETE_ME_WHERE"); context.Insert <User>(u); Assert.AreEqual(context.Get <User>(u.Id).Name, "DELETE_ME_WHERE"); // List<SqlParameter> parameters = new List<SqlParameter>(); DynamicParameters parameters = new DynamicParameters(); parameters.Add("@Name", "DELETE_ME_WHERE"); int res = context.Delete <User>("WHERE Name=@Name", parameters); Assert.AreEqual(res, 1); Assert.IsNull(context.Get <User>(u.Id)); }
public ServiceResult Delete(INode n, bool purge = false) { ServiceResult res = ServiceResponse.OK(); if (n == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(n, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var s = (Category)n; List <Category> pms = new List <Category>(); if (purge) { using (var context = new TreeMonDbContext(this._connectionKey)) { if (context.Delete <Category>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } } //get the Category from the table with all the data so when its updated it still contains the same data. s = (Category)this.GetBy(s.UUID); if (s == null) { return(ServiceResponse.Error("Symptom not found")); } s.Deleted = true; using (var context = new TreeMonDbContext(this._connectionKey)) { if (context.Update <Category>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } return(res); }
/// <summary> /// Method to validate token against expiry and existence in database. /// </summary> /// <param name="tokenId"></param> /// <returns></returns> public bool IsValidSession(string authToken) { if (string.IsNullOrEmpty(authToken)) { return(false); } UserSession us = null; using (var context = new TreeMonDbContext(_connectionKey)) { try { us = context.GetAll <UserSession>().OrderByDescending(ob => ob.Issued).FirstOrDefault(w => w.AuthToken == authToken); } catch (Exception ex) { _logger.InsertError(ex.Message, "SessionManager", "IsValidSession"); Debug.Assert(false, ex.Message); return(false); } if (us == null) { return(false); } double secondsLeft = us.Expires.Subtract(DateTime.UtcNow).TotalSeconds; if (us.IsPersistent == false && secondsLeft <= 0) { context.Delete <UserSession>(us); return(false); } if (us.SessionLength != SessionLength) { us.SessionLength = this.SessionLength; } //This adds time to the session so it won't cut them off while they're working (non idle user). us.Expires = DateTime.UtcNow.AddMinutes(us.SessionLength); context.Update <UserSession>(us); } return(true); }
public ServiceResult Delete(INode n, bool purge = false) //TODO check if finance account references this currency. if so then return error. { ServiceResult res = ServiceResponse.OK(); if (n == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(n, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } var p = (Currency)n; try { // List<SqlParameter> parameters = new List<SqlParameter>(); DynamicParameters parameters = new DynamicParameters(); parameters.Add("@UUID", p.UUID); using (var context = new TreeMonDbContext(this._connectionKey)) { if (context.Delete <Currency>("WHERE UUID=@UUID", parameters) == 0) { return(ServiceResponse.Error(p.Name + " failed to delete. ")); } } //SQLITE //this was the only way I could get it to delete a RolePermission without some stupid EF error. //object[] paramters = new object[] { rp.PermissionUUID , rp.RoleUUID ,rp.AccountUUID }; //context.Delete<RolePermission>("WHERE PermissionUUID=? AND RoleUUID=? AND AccountUUID=?", paramters); // context.Delete<RolePermission>(rp); } catch (Exception ex) { _logger.InsertError(ex.Message, "ItemManager", "DeleteItem"); Debug.Assert(false, ex.Message); return(ServiceResponse.Error("Exception occured while deleting this record.")); } return(res); }
public ServiceResult Delete(INode n, bool purge = false) { ServiceResult res = ServiceResponse.OK(); if (n == null) { return(ServiceResponse.Error("No record sent.")); } var s = (EmailLog)n; List <EmailLog> pms = new List <EmailLog>(); if (purge) { using (var context = new TreeMonDbContext(_dbConnectionKey)) { if (context.Delete <EmailLog>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } } //get the EmailLog from the table with all the data so when its updated it still contains the same data. s = (EmailLog)this.GetBy(s.UUID); if (s == null) { return(ServiceResponse.Error("Email log not found")); } s.Deleted = true; using (var context = new TreeMonDbContext(_dbConnectionKey)) { if (context.Update <EmailLog>(s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } return(res); }
public ServiceResult Delete(string userUUID, bool purge = false) { try { User u = new User(); using (var context = new TreeMonDbContext(this._connectionKey)) { u = context.GetAll <User>().FirstOrDefault(w => w.UUID == userUUID); if (u == null) { return(ServiceResponse.Error("User not found.")); } if (!this.DataAccessAuthorized(u, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } if (!DataAccessAuthorized(u, "delete", false)) { return(ServiceResponse.Error("You are not authorized access to ." + u.Name)); } if (!purge) { u.Deleted = true; return(Update(u)); } context.Delete <User>(u); } } catch (Exception ex) { _logger.InsertError(ex.Message, "UserManager", "DeleteUser:" + userUUID); Debug.Assert(false, ex.Message); return(ServiceResponse.Error(ex.Message)); } return(ServiceResponse.OK()); }
public ServiceResult Delete(INode s, bool purge = false) { ServiceResult res = ServiceResponse.OK(); if (s == null) { return(ServiceResponse.Error("No record sent.")); } if (!this.DataAccessAuthorized(s, "DELETE", false)) { return(ServiceResponse.Error("You are not authorized this action.")); } using (var context = new TreeMonDbContext(this._connectionKey)) { if (purge) { if (context.Delete <Strain>((Strain)s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } //get the strain from the table with all the data so when its updated it still contains the same data. s = this.GetBy(s.UUID); if (s == null) { ServiceResponse.Error("Strain not found."); } s.Deleted = true; if (context.Update <Strain>((Strain)s) == 0) { return(ServiceResponse.Error(s.Name + " failed to delete. ")); } } return(res); }
public ServiceResult Delete(INode n, bool purge = false) { if (n == null) { return(ServiceResponse.Error("No record sent.")); } var s = (UnitOfMeasure)n; using (var context = new TreeMonDbContext(this._connectionKey)) { if (purge) { if (context.Delete <UnitOfMeasure>(s) > 0) { return(ServiceResponse.OK()); } return(ServiceResponse.Error("Failed to purge record.")); } //get the UnitOfMeasure from the table with all the data so when its updated it still contains the same data. s = (UnitOfMeasure)this.GetBy(s.UUID); if (s == null) { return(ServiceResponse.Error("Measure not found.")); } s.Deleted = true; if (context.Update <UnitOfMeasure>(s) > 0) { return(ServiceResponse.OK()); } return(ServiceResponse.Error("Failed to delete record.")); } }
public ServiceResult DeleteCart(string cartUUID) { List <dynamic> cartItems = this.GetItemsInCart(cartUUID); foreach (dynamic item in cartItems) { //Call the delete cart item function because it will add the items back to the inventory. ServiceResult res = this.DeleteCartItem(item.CartItemUUID); if (res.Code != 200) { return(res); } } using (var context = new TreeMonDbContext(this._connectionKey)) { try { ShoppingCart cart = context.GetAll <ShoppingCart>().FirstOrDefault(w => w.UUID == cartUUID); if (cart == null) { return(ServiceResponse.Error("Shopping cart wasn't found")); } if (context.Delete <ShoppingCart>(cart) > 0) { return(ServiceResponse.OK("Cart deleted")); } } catch (Exception ex) { _logger.InsertError(ex.Message, "AddCart", MethodInfo.GetCurrentMethod().Name); } } return(ServiceResponse.Error("Shopping cart not deleted.")); }
public ServiceResult AddCartItem(string cartUUID, string cartItemUUID, float quantity) { InventoryManager inventoryManager = new InventoryManager(this._connectionKey, _sessionKey); ShoppingCartItem cartItem = this.GetCartItem(cartItemUUID); if (cartItem == null) { return(ServiceResponse.Error("Item not found in cart.")); } InventoryItem item = (InventoryItem)inventoryManager.GetBy(cartItem.ItemUUID); if (item == null) { return(ServiceResponse.Error("Product wasn't found.")); } int itemsInCart = 0; float remainingStock = 0; if (!item.Virtual) { if (item.Quantity <= 0) { return(ServiceResponse.Error("The product " + item.Name + " is sold out.")); } //If the amount requested is greater than whats in stock then set the ammount ordered to the amount on hand. if (item.Quantity < quantity) { quantity = item.Quantity; } cartItem.Quantity += quantity; //add to cart quantity item.Quantity -= quantity; //remove from inventory } User u = this.GetUser(_sessionKey); string trackingID = u == null ? _sessionKey : u.UUID; using (var transactionScope = new TransactionScope()) using (var dbContext = new TreeMonDbContext(this._connectionKey)) { try { if (cartItem.Quantity <= 0 && dbContext.Delete <ShoppingCartItem>(cartItem) <= 0) { _logger.InsertError("Failed to delete shopping cart item. " + cartItem.UUID, "StoreManager", MethodInfo.GetCurrentMethod().Name); return(ServiceResponse.Error("Failed to update shopping cart.")); } else { int changeCount = dbContext.Update <ShoppingCartItem>(cartItem); // if (dbContext.Update<ShoppingCartItem>(cartItem) <= 0) //{ // _logger.InsertError("Failed to update shopping cart. " + cartItem.UUID, "StoreManager", MethodInfo.GetCurrentMethod().Name); // return ServiceResponse.Error("Failed to update shopping cart."); //} } if (dbContext.Update <InventoryItem>(item) <= 0) { _logger.InsertError("Failed to update inventory. " + item.UUID, "StoreManager", MethodInfo.GetCurrentMethod().Name); return(ServiceResponse.Error("Failed to update inventory.")); } transactionScope.Complete(); remainingStock = item.Quantity; } catch (Exception ex) { _logger.InsertError(ex.Message, "StoreManager", MethodInfo.GetCurrentMethod().Name); } itemsInCart = dbContext.GetAll <ShoppingCartItem>().Where(w => w.UserUUID == trackingID).Count(); } return(ServiceResponse.OK("", "{ \"CartUUID\" :\"" + trackingID + "\", \"CartItemUUID\" :\"" + cartItem.UUID + "\", \"RemainingStock\" : \"" + remainingStock + "\", \"IsVirtual\" : \"" + item.Virtual + "\" , \"ItemsInCart\" : \"" + itemsInCart + "\" }")); }
//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)); }