Exemplo n.º 1
0
Arquivo: DB.cs Projeto: Skovmissen/MCB
        public static List <FinanceAccount> GetAllFinanceAccounts(int id) // Lavet af Nikolaj
        {
            OpenDb();
            List <FinanceAccount> Accounts = new List <FinanceAccount>();
            SqlCommand            command  = new SqlCommand("SELECT * From FinanceAccount WHERE BudgetId = @BudgetId", connection);

            command.Parameters.AddWithValue("@BudgetId", id);
            try
            {
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    FinanceAccount p = new FinanceAccount();
                    p.AccountId    = (int)reader["AccountId"];
                    p.Name         = (string)reader["Name"];
                    p.FinanceGroup = (string)reader["FinancegroupName"];
                    p.BudgetId     = (int)reader["BudgetId"];
                    p.ArticleId    = (string)reader["ArticleId"];
                    Accounts.Add(p);
                }
                CloseDb();
                return(Accounts);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 2
0
        public ServiceResult Insert(FinanceAccount n)
        {
            if (CurrentUser == null)
            {
                return(ServiceResponse.Error("You must be logged in to access this function."));
            }

            if (string.IsNullOrWhiteSpace(n.AccountUUID) || n.AccountUUID == SystemFlag.Default.Account)
            {
                n.AccountUUID = CurrentUser.AccountUUID;
            }

            if (string.IsNullOrWhiteSpace(n.CreatedBy))
            {
                n.CreatedBy = CurrentUser.UUID;
            }

            if (n.DateCreated == DateTime.MinValue)
            {
                n.DateCreated = DateTime.UtcNow;
            }

            FinanceAccountManager FinanceAccountManager = new FinanceAccountManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

            return(FinanceAccountManager.Insert(n));
        }
Exemplo n.º 3
0
        protected virtual async Task CreateUserAsync(CreateOrUpdateUserInput input)
        {
            if (AbpSession.TenantId.HasValue)
            {
                await _userPolicy.CheckMaxUserCountAsync(AbpSession.GetTenantId());
            }

            var user = input.User.MapTo <User>(); //Passwords is not mapped (see mapping configuration)

            user.TenantId = AbpSession.TenantId;

            //Set password
            if (!input.User.Password.IsNullOrEmpty())
            {
                CheckErrors(await UserManager.PasswordValidator.ValidateAsync(input.User.Password));
            }
            else
            {
                input.User.Password = User.CreateRandomPassword();
            }

            user.Password = new PasswordHasher().HashPassword(input.User.Password);
            user.ShouldChangePasswordOnNextLogin = input.User.ShouldChangePasswordOnNextLogin;

            //Assign roles
            user.Roles = new Collection <UserRole>();
            foreach (var roleName in input.AssignedRoleNames)
            {
                var role = await _roleManager.GetRoleByNameAsync(roleName);

                user.Roles.Add(new UserRole(AbpSession.TenantId, user.Id, role.Id));
            }

            CheckErrors(await UserManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync(); //To get new user's Id.

            FinanceAccount account = new FinanceAccount();

            account.UserId        = user.Id;
            account.Advance       = 0;
            account.AdvanceForzen = 0;
            account.Blance        = 0;
            account.BlanceFrozen  = 0;
            account.IsActive      = true;
            await _financeAccountRepository.InsertAsync(account);

            //Notifications
            await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            //Send activation email
            if (input.SendActivationEmail)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(user, input.User.Password);
            }
        }
Exemplo n.º 4
0
        public ServiceResult Update(FinanceAccount s)
        {
            if (s == null)
            {
                return(ServiceResponse.Error("Invalid FinanceAccount sent to server."));
            }

            FinanceAccountManager FinanceAccountManager = new FinanceAccountManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            var res = FinanceAccountManager.Get(s.UUID);

            if (res.Code != 200)
            {
                return(res);
            }

            var dbS = (FinanceAccount)res.Result;

            if (dbS.DateCreated == DateTime.MinValue)
            {
                dbS.DateCreated = DateTime.UtcNow;
            }

            dbS.Deleted       = s.Deleted;
            dbS.Name          = s.Name;
            dbS.Status        = s.Status;
            dbS.SortOrder     = s.SortOrder;
            dbS.AccountNumber = s.AccountNumber;
            dbS.CurrencyUUID  = s.CurrencyUUID;
            dbS.Balance       = s.Balance;
            dbS.Active        = s.Active;
            dbS.LocationType  = s.LocationType;
            dbS.ClientCode    = s.ClientCode;

            if (string.IsNullOrWhiteSpace(s.Image) || s.Image.EndsWith("/"))
            {
                dbS.Image = "/Content/Default/Images/bank.png";
            }
            else
            {
                dbS.Image = s.Image;
            }
            //
            //   AssetClass
            // Balance
            //
            //CurrencyName
            //  IsTest
            //Password
            //ServiceAddress
            //SourceClass
            //SourceUUID
            //  UsedBy
            //UsedByClass
            return(FinanceAccountManager.Update(dbS));
        }
        public async Task <IEnumerable <Transaction> > LoadTransactionsAsync(FinanceAccount accountToLoadFrom)
        {
            IEnumerable <Transaction> transactionsToReturn = null;
            bool fileExists = await _objectHelper.FileExistsAsync($"{accountToLoadFrom.Name}{AccountTransactionExtension}");

            if (fileExists)
            {
                transactionsToReturn = await _objectHelper.ReadFileAsync(AccountsFileName, default(IEnumerable <Transaction>));
            }
            return(transactionsToReturn);
        }
Exemplo n.º 6
0
        public ServiceResult GetBy(string uuid)
        {
            if (string.IsNullOrWhiteSpace(uuid))
            {
                return(ServiceResponse.Error("You must provide a uuid for the FinanceAccount."));
            }

            FinanceAccountManager FinanceAccountManager = new FinanceAccountManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);

            FinanceAccount s = (FinanceAccount)FinanceAccountManager.GetBy(uuid);

            if (s == null)
            {
                return(ServiceResponse.Error("FinanceAccount could not be located for the uuid " + uuid));
            }

            return(ServiceResponse.OK("", s));
        }
Exemplo n.º 7
0
        public ServiceResult Delete(FinanceAccount n)
        {
            if (n == null)
            {
                return(ServiceResponse.Error("Invalid account was sent."));
            }

            FinanceAccountManager FinanceAccountManager = new FinanceAccountManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter);

            FinanceAccount fa = (FinanceAccount)FinanceAccountManager.GetBy(n.UUID);

            if (fa == null)
            {
                return(ServiceResponse.Error("Could not find finance account."));
            }

            return(FinanceAccountManager.Delete(fa));
        }
Exemplo n.º 8
0
        public ServiceResult Delete(FinanceAccount n)
        {
            if (n == null)
            {
                return(ServiceResponse.Error("Invalid account was sent."));
            }

            FinanceAccountManager FinanceAccountManager = new FinanceAccountManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            var res = FinanceAccountManager.Get(n.UUID);

            if (res.Code != 200)
            {
                return(res);
            }

            FinanceAccount fa = (FinanceAccount)res.Result;

            return(FinanceAccountManager.Delete(fa));
        }
Exemplo n.º 9
0
        public ServiceResult Delete(string uuid)
        {
            if (string.IsNullOrWhiteSpace(uuid))
            {
                return(ServiceResponse.Error("Invalid account was sent."));
            }

            FinanceAccountManager FinanceAccountManager = new FinanceAccountManager(Globals.DBConnectionKey, this.GetAuthToken(Request));
            var res = FinanceAccountManager.Get(uuid);

            if (res.Code != 200)
            {
                return(res);
            }

            FinanceAccount fa = (FinanceAccount)res.Result;

            return(FinanceAccountManager.Delete(fa));
        }
        public async Task <IActionResult> Post([FromBody] FinanceAccount account)
        {
            if (!ModelState.IsValid)
            {
                HIHAPIUtility.HandleModalStateError(ModelState);
            }

            // User
            String usrName = String.Empty;

            try
            {
                usrName = HIHAPIUtility.GetUserID(this);
                if (String.IsNullOrEmpty(usrName))
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch
            {
                throw new UnauthorizedAccessException();
            }

            // Check whether User assigned with specified Home ID
            var hms = _context.HomeMembers.Where(p => p.HomeID == account.HomeID && p.User == usrName).Count();

            if (hms <= 0)
            {
                throw new UnauthorizedAccessException();
            }

            if (!account.IsValid(this._context))
            {
                return(BadRequest());
            }

            account.CreatedAt = DateTime.Now;
            account.Createdby = usrName;
            _context.FinanceAccount.Add(account);
            await _context.SaveChangesAsync();

            return(Created(account));
        }
Exemplo n.º 11
0
        /// <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 = (FinanceAccount)n;

            if (validateFirst)
            {
                FinanceAccount dbU = (FinanceAccount)Get(p.Name);

                if (dbU != null)
                {
                    return(ServiceResponse.Error("FinanceAccount 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 <FinanceAccount>(p))
                {
                    return(ServiceResponse.OK("", p));
                }
            }
            return(ServiceResponse.Error("An error occurred inserting product " + p.Name));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> PostAssetBuyDocument([FromBody] FinanceAssetBuyDocumentCreateContext createContext)
        {
            if (!ModelState.IsValid)
            {
                HIHAPIUtility.HandleModalStateError(ModelState);
            }

            if (createContext == null || createContext.ExtraAsset == null)
            {
                throw new BadRequestException("No data is inputted");
            }
            if (createContext.HID <= 0)
            {
                throw new BadRequestException("Not HID inputted");
            }

            // User
            String usrName = String.Empty;

            try
            {
                usrName = HIHAPIUtility.GetUserID(this);
                if (String.IsNullOrEmpty(usrName))
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch
            {
                throw new UnauthorizedAccessException();
            }
            // Check whether User assigned with specified Home ID
            var hms = _context.HomeMembers.Where(p => p.HomeID == createContext.HID && p.User == usrName).Count();

            if (hms <= 0)
            {
                throw new UnauthorizedAccessException();
            }

            // Do basic checks
            if (String.IsNullOrEmpty(createContext.TranCurr) || String.IsNullOrEmpty(createContext.ExtraAsset.Name))
            {
                throw new BadRequestException("Invalid input data");
            }
            if (createContext.IsLegacy.HasValue && createContext.IsLegacy.Value)
            {
                if (createContext.Items.Count > 0)
                {
                    throw new BadRequestException("Invalid input data");
                }
            }
            else
            {
                if (createContext.Items.Count <= 0)
                {
                    throw new BadRequestException("Invalid input data");
                }
            }

            foreach (var di in createContext.Items)
            {
                if (di.TranAmount == 0 || di.AccountID <= 0 || di.TranType <= 0 || (di.ControlCenterID <= 0 && di.OrderID <= 0))
                {
                    throw new BadRequestException("Invalid input data in items!");
                }
            }

            // Construct the Account
            var vmAccount = new FinanceAccount();

            vmAccount.HomeID                   = createContext.HID;
            vmAccount.Name                     = createContext.ExtraAsset.Name;
            vmAccount.Status                   = (Byte)FinanceAccountStatus.Normal;
            vmAccount.CategoryID               = FinanceAccountCategory.AccountCategory_Asset;
            vmAccount.ExtraAsset               = new FinanceAccountExtraAS();
            vmAccount.Owner                    = createContext.AccountOwner;
            vmAccount.Comment                  = createContext.ExtraAsset.Comment;
            vmAccount.ExtraAsset.Name          = createContext.ExtraAsset.Name;
            vmAccount.ExtraAsset.Comment       = createContext.ExtraAsset.Comment;
            vmAccount.ExtraAsset.CategoryID    = createContext.ExtraAsset.CategoryID;
            vmAccount.ExtraAsset.AccountHeader = vmAccount;

            // Construct the Doc.
            var vmFIDoc = new FinanceDocument();

            vmFIDoc.DocType  = FinanceDocumentType.DocType_AssetBuyIn;
            vmFIDoc.Desp     = createContext.Desp;
            vmFIDoc.TranDate = createContext.TranDate;
            vmFIDoc.HomeID   = createContext.HID;
            vmFIDoc.TranCurr = createContext.TranCurr;

            var maxItemID = 0;

            if (createContext.IsLegacy.HasValue && createContext.IsLegacy.Value)
            {
                // Legacy account...
            }
            else
            {
                Decimal totalAmt = 0;
                foreach (var di in createContext.Items)
                {
                    if (di.ItemID <= 0 || di.TranAmount == 0 || di.AccountID <= 0 ||
                        (di.ControlCenterID <= 0 && di.OrderID <= 0))
                    {
                        throw new BadRequestException("Invalid input data in items!");
                    }

                    // Todo: new check the tran. type is an expense!

                    totalAmt += di.TranAmount;
                    vmFIDoc.Items.Add(di);

                    if (maxItemID < di.ItemID)
                    {
                        maxItemID = di.ItemID;
                    }
                }

                if (totalAmt != createContext.TranAmount)
                {
                    throw new BadRequestException("Amount is not even");
                }
            }

            // Database update
            var errorString    = "";
            var errorOccur     = false;
            var origdocid      = 0;
            var assetaccountid = 0;

            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    // 1. Create the document
                    vmFIDoc.Createdby = usrName;
                    vmFIDoc.CreatedAt = DateTime.Now;
                    var docEntity = _context.FinanceDocument.Add(vmFIDoc);
                    await _context.SaveChangesAsync();

                    origdocid = docEntity.Entity.ID;

                    // 2, Create the account
                    vmAccount.ExtraAsset.RefenceBuyDocumentID = origdocid;
                    vmAccount.CreatedAt = DateTime.Now;
                    vmAccount.Createdby = usrName;
                    var acntEntity = _context.FinanceAccount.Add(vmAccount);
                    await _context.SaveChangesAsync();

                    assetaccountid = acntEntity.Entity.ID;

                    // 3. Update the document by adding one more item
                    var nitem = new FinanceDocumentItem();
                    nitem.ItemID     = ++maxItemID;
                    nitem.AccountID  = assetaccountid;
                    nitem.TranAmount = createContext.TranAmount;
                    nitem.Desp       = vmFIDoc.Desp;
                    nitem.TranType   = FinanceTransactionType.TranType_OpeningAsset;
                    if (createContext.ControlCenterID.HasValue)
                    {
                        nitem.ControlCenterID = createContext.ControlCenterID.Value;
                    }
                    if (createContext.OrderID.HasValue)
                    {
                        nitem.OrderID = createContext.OrderID.Value;
                    }
                    nitem.DocumentHeader = vmFIDoc;
                    docEntity.Entity.Items.Add(nitem);

                    docEntity.State = EntityState.Modified;

                    await _context.SaveChangesAsync();

                    vmFIDoc = docEntity.Entity;

                    transaction.Commit();
                }
                catch (Exception exp)
                {
                    errorOccur  = true;
                    errorString = exp.Message;
                    transaction.Rollback();
                }
            }

            if (errorOccur)
            {
                throw new BadRequestException(errorString);
            }

            return(Created(vmFIDoc));
        }
Exemplo n.º 13
0
        private ServiceResult SendEmail(CartView cart, Order order, FinanceAccount account, string customerEmail, string status)
        {
            if (cart == null)
            {
                return(ServiceResponse.Error("Could not send email, cart was not set."));
            }

            AppManager am           = new AppManager(this._connectionKey, "web", this._sessionKey);
            string     domain       = am.GetSetting("SiteDomain")?.Value;
            string     emailSubject = "";
            string     emailContent = "";

            //todo put this in another function
            #region get email content function

            switch (status)
            {
            case StoreFlag.OrderStatus.Recieved:
                emailSubject = "Your " + domain + " order has been recieved.";

                DocumentManager dm = new DocumentManager(this._connectionKey, SessionKey);
                emailContent = dm.GetTemplate("EmailOrderReceived").Result?.ToString();

                if (string.IsNullOrWhiteSpace(emailContent))
                {
                    return(ServiceResponse.Error("Failed to send email. Document not found."));
                }

                //use view cart for details
                emailContent = emailContent.Replace("[Order.OrderID]", order.UUID);
                emailContent = emailContent.Replace("[Order.AddedDate]", order.DateCreated.ToShortDateString());
                //See below: emailContent = emailContent.Replace( "[Order.Total]"                  ,
                emailContent = emailContent.Replace("[PaymentType.Title]", cart.PaidType);
                emailContent = emailContent.Replace("[StoreManager.PayType]", account.CurrencyName);
                emailContent = emailContent.Replace("[StoreManager.PayTypeTotal]", order.Total.ToString());
                //emailContent = emailContent.Replace( "                               ,PayTypeSubTotal);
                // emailContent = emailContent.Replace("[PayType.Address]", account. PayType.Address);
                emailContent = emailContent.Replace("[PayType.PictureUrl]", account.Image);
                emailContent = emailContent.Replace("[Settings.CurrencySymbol]", am.GetSetting("default.currency.symbol").Value);
                emailContent = emailContent.Replace("[Settings.SiteDomain]", domain);

                //todo  paytype.address and qr code for btc.
                //todo bookmark latest currency symbol
                // string validationCode = Cipher.RandomString(12);
                //   emailContent = emailContent.Replace("[Url.Unsubscribe]", "http://" + domain + "/FinanceAccount/ValidateEmail/?type=mbr&operation=mdel&code=" + validationCode);

                StringBuilder ShoppingCartItemsList = new StringBuilder();

                foreach (dynamic item in cart.CartItems)
                {
                    ShoppingCartItemsList.Append("<tr id=\"[item-ShoppingCartItem.Product.Id]\">".Replace("[item-ShoppingCartItem.Product.ProductID]", item.ItemUUID.ToString()));
                    ShoppingCartItemsList.Append("<td align=\"center\">[ShoppingCartItem.Title]</td>".Replace("[ShoppingCartItem.Title]", item.Name.ToString()));
                    ShoppingCartItemsList.Append("<td align=\"center\">[ShoppingCartItem.Quantity]</td>".Replace("[ShoppingCartItem.Quantity]", item.Quantity.ToString()));
                    ShoppingCartItemsList.Append("<td align=\"center\">[ShoppingCartItem.Price]</td></tr>".Replace("[ShoppingCartItem.Price]", item.Price.ToString("c")));
                }

                emailContent = emailContent.Replace("[ShoppingCartItemsList]", ShoppingCartItemsList.ToString());
                emailContent = emailContent.Replace("[Order.SubTotal]", order.SubTotal.ToString("c"));
                emailContent = emailContent.Replace("[Order.Total]", order.Total.ToString("c"));
                #endregion
                break;
            }
            string appKey        = am.GetSetting("AppKey")?.Value;
            string emailPassword = am.GetSetting("EmailHostPassword")?.Value;

            SMTP mailServer = new SMTP(this._connectionKey, new Models.Services.EmailSettings()
            {
                HostPassword  = Cipher.Crypt(appKey, emailPassword, false),
                EncryptionKey = am.GetSetting("AppKey")?.Value,
                HostUser      = am.GetSetting("EmailHostUser")?.Value,
                MailHost      = am.GetSetting("MailHost")?.Value,
                MailPort      = StringEx.ConvertTo <int>(am.GetSetting("MailPort")?.Value),
                SiteDomain    = am.GetSetting("SiteDomain")?.Value,
                SiteEmail     = am.GetSetting("SiteEmail")?.Value,
                UseSSL        = StringEx.ConvertTo <bool>(am.GetSetting("UseSSL")?.Value)
            });
            MailMessage mail = new MailMessage();
            try
            {
                mail.From = new MailAddress(am.GetSetting("SiteEmail")?.Value);
                mail.ReplyToList.Add(mail.From);
                mail.To.Add(customerEmail);
                mail.Subject    = emailSubject;
                mail.Body       = emailContent;
                mail.IsBodyHtml = true;
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
                this._logger.InsertError(ex.Message, "StoreManager", "SendMail");
                return(ServiceResponse.Error("Failed to send email. "));
            }

            ServiceResult res = mailServer.SendMail(mail);
            if (res.Code != 200)
            {
                Debug.Assert(false, mailServer.ErrorMessage);
                this._logger.InsertError(mailServer.ErrorMessage, "StoreManager", "SendMail");
                return(ServiceResponse.Error("Failed to send email. "));
            }
            return(ServiceResponse.OK());
        }
        public async Task <IActionResult> Put([FromODataUri] int key, [FromBody] FinanceAccount update)
        {
            if (!ModelState.IsValid)
            {
                HIHAPIUtility.HandleModalStateError(ModelState);
            }

            if (key != update.ID)
            {
                throw new BadRequestException("ID mismatched");
            }

            // User
            String usrName = String.Empty;

            try
            {
                usrName = HIHAPIUtility.GetUserID(this);
                if (String.IsNullOrEmpty(usrName))
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch
            {
                throw new UnauthorizedAccessException();
            }

            // Check whether User assigned with specified Home ID
            var hms = _context.HomeMembers.Where(p => p.HomeID == update.HomeID && p.User == usrName).Count();

            if (hms <= 0)
            {
                throw new UnauthorizedAccessException();
            }

            if (!update.IsValid(this._context))
            {
                return(BadRequest());
            }

            update.Updatedby             = usrName;
            update.UpdatedAt             = DateTime.Now;
            _context.Entry(update).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException exp)
            {
                if (!_context.FinanceAccount.Any(p => p.ID == key))
                {
                    return(NotFound());
                }
                else
                {
                    throw new DBOperationException(exp.Message);
                }
            }

            return(Updated(update));
        }
Exemplo n.º 15
0
        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");
            }
        }
Exemplo n.º 16
0
        public async Task TestCase1_NormalAccount(int hid, string user, int ctgyid)
        {
            var context   = this.fixture.GetCurrentDataContext();
            var secondhid = hid;

            // 0. Initialize data
            if (hid == DataSetupUtility.Home1ID)
            {
                if (user == DataSetupUtility.UserA || user == DataSetupUtility.UserB)
                {
                    secondhid = DataSetupUtility.Home3ID;
                }
                else if (user == DataSetupUtility.UserC)
                {
                    secondhid = DataSetupUtility.Home4ID;
                }
                else if (user == DataSetupUtility.UserD)
                {
                    secondhid = DataSetupUtility.Home5ID;
                }
            }
            else if (hid == DataSetupUtility.Home2ID)
            {
                secondhid = DataSetupUtility.Home3ID;
            }

            if (hid == DataSetupUtility.Home1ID || secondhid == DataSetupUtility.Home1ID)
            {
                fixture.InitHome1TestData(context);
            }
            if (hid == DataSetupUtility.Home2ID || secondhid == DataSetupUtility.Home2ID)
            {
                fixture.InitHome2TestData(context);
            }
            if (hid == DataSetupUtility.Home3ID || secondhid == DataSetupUtility.Home3ID)
            {
                fixture.InitHome3TestData(context);
            }
            if (hid == DataSetupUtility.Home4ID || secondhid == DataSetupUtility.Home4ID)
            {
                fixture.InitHome4TestData(context);
            }
            if (hid == DataSetupUtility.Home5ID || secondhid == DataSetupUtility.Home5ID)
            {
                fixture.InitHome5TestData(context);
            }

            // 0a. Prepare the context
            var control   = new FinanceAccountsController(context);
            var userclaim = DataSetupUtility.GetClaimForUser(user);
            var httpctx   = UnitTestUtility.GetDefaultHttpContext(provider, userclaim);

            control.ControllerContext = new ControllerContext()
            {
                HttpContext = httpctx
            };
            var curhmemquery = (from homemem in context.HomeMembers where homemem.HomeID == hid && homemem.User == user select homemem).FirstOrDefault();
            var curhmem      = Assert.IsType <HomeMember>(curhmemquery);
            var acntamt      = (from homemem in context.HomeMembers
                                join finacnt in context.FinanceAccount
                                on new { homemem.HomeID, homemem.User } equals new { finacnt.HomeID, User = user }
                                select finacnt.ID).ToList().Count();

            // 1. Create first account
            var acnt = new FinanceAccount()
            {
                HomeID     = hid,
                Name       = "Account_" + ctgyid.ToString() + ".1",
                CategoryID = ctgyid,
                Owner      = user
            };
            var rst = await control.Post(acnt);

            Assert.NotNull(rst);
            var rst2 = Assert.IsType <CreatedODataResult <FinanceAccount> >(rst);

            Assert.Equal(rst2.Entity.Name, acnt.Name);
            Assert.Equal(rst2.Entity.HomeID, acnt.HomeID);
            Assert.Equal(rst2.Entity.CategoryID, acnt.CategoryID);
            Assert.Equal(rst2.Entity.Owner, user);
            var firstacntid = rst2.Entity.ID;

            Assert.True(firstacntid > 0);
            accountsCreated.Add(firstacntid);

            // 2. Now read the whole accounts (no home ID applied)
            var queryUrl     = "http://localhost/api/FinanceAccounts";
            var req          = UnitTestUtility.GetHttpRequest(httpctx, "GET", queryUrl);
            var odatacontext = UnitTestUtility.GetODataQueryContext <FinanceAccount>(this.model);
            var options      = UnitTestUtility.GetODataQueryOptions <FinanceAccount>(odatacontext, req);
            var rst3         = control.Get(options);

            Assert.NotNull(rst3);
            if (curhmem.IsChild.HasValue && curhmem.IsChild == true)
            {
                acntamt = context.FinanceAccount.Where(p => p.Owner == curhmem.User).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }
            else
            {
                Assert.Equal(acntamt + 1, rst3.Cast <FinanceAccount>().Count());
            }

            // 2a. Read the whole accounts (with home ID applied)
            queryUrl = "http://localhost/api/FinanceAccounts?$filter=HomeID eq " + hid.ToString();
            req      = UnitTestUtility.GetHttpRequest(httpctx, "GET", queryUrl);
            //var odatacontext = UnitTestUtility.GetODataQueryContext<FinanceAccount>(this.model);
            options = UnitTestUtility.GetODataQueryOptions <FinanceAccount>(odatacontext, req);
            rst3    = control.Get(options);
            Assert.NotNull(rst3);
            if (curhmem.IsChild.HasValue && curhmem.IsChild == true)
            {
                acntamt = context.FinanceAccount.Where(p => p.HomeID == hid && p.Owner == curhmem.User).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }
            else
            {
                acntamt = context.FinanceAccount.Where(p => p.HomeID == hid).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }

            // 3. Now create another one!
            acnt = new FinanceAccount()
            {
                HomeID     = hid,
                Name       = "Account_" + ctgyid.ToString() + ".2",
                Comment    = "Comment 2",
                CategoryID = ctgyid,
                Owner      = user
            };
            rst = await control.Post(acnt);

            Assert.NotNull(rst);
            rst2 = Assert.IsType <CreatedODataResult <FinanceAccount> >(rst);
            Assert.Equal(rst2.Entity.Name, acnt.Name);
            Assert.Equal(rst2.Entity.HomeID, acnt.HomeID);
            Assert.Equal(rst2.Entity.CategoryID, acnt.CategoryID);
            Assert.Equal(rst2.Entity.Owner, acnt.Owner);
            var secondacntid = rst2.Entity.ID;

            Assert.True(secondacntid > 0);
            accountsCreated.Add(secondacntid);

            // 4. Change one account
            acnt.Comment = "Comment 2 Updated";
            rst          = await control.Put(secondacntid, acnt);

            Assert.NotNull(rst);
            var rst4 = Assert.IsType <UpdatedODataResult <FinanceAccount> >(rst);

            Assert.Equal(rst4.Entity.Name, acnt.Name);
            Assert.Equal(rst4.Entity.HomeID, acnt.HomeID);
            Assert.Equal(rst4.Entity.Comment, acnt.Comment);

            // 5. Delete the second account
            var rst5 = await control.Delete(secondacntid);

            Assert.NotNull(rst5);
            var rst6 = Assert.IsType <StatusCodeResult>(rst5);

            Assert.Equal(204, rst6.StatusCode);

            // 6. Now read the whole accounts
            rst3 = control.Get(options);
            Assert.NotNull(rst3);
            if (curhmem.IsChild.HasValue && curhmem.IsChild == true)
            {
                acntamt = context.FinanceAccount.Where(p => p.HomeID == hid && p.Owner == user).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }
            else
            {
                acntamt = context.FinanceAccount.Where(p => p.HomeID == hid).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }

            // 7. Delete the first account
            rst5 = await control.Delete(firstacntid);

            Assert.NotNull(rst5);
            rst6 = Assert.IsType <StatusCodeResult>(rst5);
            Assert.Equal(204, rst6.StatusCode);

            // 8. Now read the whole accounts
            rst3 = control.Get(options);
            Assert.NotNull(rst3);
            if (curhmem.IsChild.HasValue && curhmem.IsChild == true)
            {
                acntamt = context.FinanceAccount.Where(p => p.HomeID == hid && p.Owner == user).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }
            else
            {
                acntamt = context.FinanceAccount.Where(p => p.HomeID == hid).Count();
                Assert.Equal(acntamt, rst3.Cast <FinanceAccount>().Count());
            }

            accountsCreated.Clear();

            await context.DisposeAsync();
        }
Exemplo n.º 17
0
        public async Task TestCase1()
        {
            string token = await IdentityServerSetup.Instance.GetAccessTokenForUser(DataSetupUtility.UserA, DataSetupUtility.IntegrationTestPassword);

            var clientWithAuth = _factory.CreateClient();

            clientWithAuth.SetBearerToken(token);

            // Step 1. Metadata request
            var metadata = await this._client.GetAsync("/api/$metadata");

            Assert.Equal(HttpStatusCode.OK, metadata.StatusCode);
            var content = await metadata.Content.ReadAsStringAsync();

            if (content.Length > 0)
            {
                // How to verify metadata?
                // TBD.
            }

            // Step 2. Read Home Defines - Non authority case
            var req1 = await this._client.GetAsync("/api/HomeDefines");

            Assert.Equal(HttpStatusCode.Unauthorized, req1.StatusCode);

            // Step 3. Read Home Defines - Authority case
            var resp2 = await clientWithAuth.GetAsync("/api/HomeDefines");

            Assert.True(resp2.IsSuccessStatusCode);
            string result = resp2.Content.ReadAsStringAsync().Result;

            if (!String.IsNullOrEmpty(result))
            {
                JToken outer = JToken.Parse(result);

                // Old way to deserialize the arry
                JArray inner = outer["value"].Value <JArray>();
                var    dfs   = inner.ToObject <List <HomeDefine> >();
                Assert.Equal(2, dfs.Count);

                // For user A, Home1 Is a must
                var bHome1Exist = false;
                foreach (var df in dfs)
                {
                    Assert.NotNull(df);
                    Assert.True(df.ID > 0);
                    Assert.False(String.IsNullOrEmpty(df.Name));
                    Assert.NotNull(df.HomeMembers);
                    if (df.ID == DataSetupUtility.Home1ID)
                    {
                        bHome1Exist = true;
                    }
                }
                Assert.True(bHome1Exist);
            }

            // Step 4. Read home defines - with home members
            resp2 = await clientWithAuth.GetAsync("/api/HomeDefines?$expand=HomeMembers");

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
                JToken outer = JToken.Parse(result);

                JArray inner = outer["value"].Value <JArray>();
                var    dfs   = inner.ToObject <List <HomeDefine> >();
                Assert.Equal(2, dfs.Count);

                // For user A, Home1 Is a must
                foreach (var df in dfs)
                {
                    Assert.NotNull(df);
                    Assert.True(df.ID > 0);
                    Assert.False(String.IsNullOrEmpty(df.Name));
                    Assert.NotNull(df.HomeMembers);
                    var exist = df.HomeMembers.Single(p => p.User == DataSetupUtility.UserA);
                    Assert.NotNull(exist);
                }
            }

            var hid      = DataSetupUtility.Home1ID;
            var cc1id    = 0;
            var ord1id   = 0;
            var acnt1id  = 0;
            var doc1id   = 0;
            var jsetting = new JsonSerializerSettings();

            jsetting.Converters.Add(new StringEnumConverter());
            jsetting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            jsetting.DateFormatString      = "yyyy-MM-dd";

            // Step 5. Create a control center
            var cc = new FinanceControlCenter()
            {
                HomeID  = hid,
                Name    = "Control Center 1",
                Comment = "Comment 1",
                Owner   = DataSetupUtility.UserA
            };
            var kjson        = JsonConvert.SerializeObject(cc, jsetting);
            var inputContent = new StringContent(kjson, Encoding.UTF8, "application/json");

            resp2 = await clientWithAuth.PostAsync("/api/FinanceControlCenters", inputContent);

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
                var odatarst = JsonConvert.DeserializeObject <FinanceControlCenter>(result);
                Assert.Equal(odatarst.Name, cc.Name);
                Assert.Equal(odatarst.HomeID, cc.HomeID);
                Assert.Equal(odatarst.Owner, cc.Owner);
                cc1id = odatarst.ID;
                Assert.True(cc1id > 0);
            }

            // Step 6. Create an order
            var ord = new FinanceOrder()
            {
                HomeID  = hid,
                Name    = "Order 1",
                Comment = "Comment 1"
            };
            var srule = new FinanceOrderSRule()
            {
                Order           = ord,
                RuleID          = 1,
                ControlCenterID = cc1id,
                Precent         = 100
            };

            ord.SRule.Add(srule);
            kjson        = JsonConvert.SerializeObject(ord, jsetting);
            inputContent = new StringContent(kjson, Encoding.UTF8, "application/json");
            resp2        = await clientWithAuth.PostAsync("/api/FinanceOrders", inputContent);

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
                var odatarst = JsonConvert.DeserializeObject <FinanceOrder>(result);
                Assert.Equal(odatarst.Name, ord.Name);
                ord1id = odatarst.ID;
                Assert.True(ord1id > 0);
            }

            // Step 7. Create an account
            var acnt = new FinanceAccount()
            {
                HomeID     = DataSetupUtility.Home1ID,
                Name       = "Account 1",
                CategoryID = FinanceAccountCategory.AccountCategory_Cash,
                Owner      = DataSetupUtility.UserA
            };

            kjson        = JsonConvert.SerializeObject(acnt, jsetting);
            inputContent = new StringContent(kjson, Encoding.UTF8, "application/json");
            resp2        = await clientWithAuth.PostAsync("/api/FinanceAccounts", inputContent);

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
                var odatarst = JsonConvert.DeserializeObject <FinanceAccount>(result);
                Assert.Equal(odatarst.Name, acnt.Name);
                acnt1id = odatarst.ID;
                Assert.True(acnt1id > 0);
            }

            // Step 7a. Get all accounts
            resp2 = await clientWithAuth.GetAsync("/api/FinanceAccounts?hid=" + hid.ToString());

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
                //var odatarst = JsonConvert.DeserializeObject<FinanceAccount>(result);
                //Assert.Equal(odatarst.Name, acnt.Name);
                //acnt1id = odatarst.ID;
                //Assert.True(acnt1id > 0);
            }

            // Step 7b. Read one specified account
            resp2 = await clientWithAuth.GetAsync("/api/FinanceAccounts(" + acnt1id.ToString() + ")"); // ?hid=" + hid.ToString());

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
            }

            // Step 8. Post a document
            var doc = new FinanceDocument()
            {
                DocType  = FinanceDocumentType.DocType_Normal,
                HomeID   = hid,
                TranDate = DateTime.Today,
                Desp     = "First document",
                TranCurr = DataSetupUtility.Home1BaseCurrency,
            };
            var item = new FinanceDocumentItem()
            {
                DocumentHeader  = doc,
                ItemID          = 1,
                Desp            = "Item 1.1",
                TranType        = 2, // Wage
                TranAmount      = 10,
                AccountID       = acnt1id,
                ControlCenterID = cc1id,
            };

            doc.Items.Add(item);
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            kjson        = JsonConvert.SerializeObject(doc, jsetting);
            inputContent = new StringContent(kjson, Encoding.UTF8, "application/json");
            resp2        = await clientWithAuth.PostAsync("/api/FinanceDocuments", inputContent);

            Assert.True(resp2.IsSuccessStatusCode);
            result = resp2.Content.ReadAsStringAsync().Result;
            if (!String.IsNullOrEmpty(result))
            {
                var odatarst = JsonConvert.DeserializeObject <FinanceDocument>(result);
                Assert.Equal(odatarst.Desp, doc.Desp);
                doc1id = odatarst.ID;
                Assert.True(doc1id > 0);
            }

            // Step 9. Create an ADP document
            //var adpcontext = new FinanceADPDocumentCreateContext();
            //adpcontext.DocumentInfo = new FinanceDocument();
            //adpcontext.AccountInfo = new FinanceAccount();
        }
Exemplo n.º 18
0
        //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));
        }