Beispiel #1
0
        public TransferDetails GetTransferDetails(int transferid)
        {
            TransferDetails details = new TransferDetails();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand("select ts.transfer_status_desc, tt.transfer_type_desc, t.account_to, t.account_from, amount from transfers t join transfer_statuses ts on t.transfer_status_id = ts.transfer_status_id join transfer_types tt on t.transfer_type_id = ts.transfer_status_id where t.transfer_id = @transferId", connection);
                    command.Parameters.AddWithValue("@transferid", transferid);
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        details.TransferId   = transferid;
                        details.TransferType = Convert.ToString(reader["transfer_type_desc"]);
                        details.StatusDesc   = Convert.ToString(reader["transfer_status_desc"]);
                        UserSqlDAO dao    = new UserSqlDAO(connectionString);
                        int        fromId = Convert.ToInt16(reader["account_from"]);
                        details.FromUsername = dao.GetUserByID(fromId).Username;
                        int toId = Convert.ToInt16(reader["account_to"]);
                        details.ToUsername = dao.GetUserByID(toId).Username;
                        details.Amount     = Convert.ToDecimal(reader["amount"]);
                    }
                    return(details);
                }
            }
            catch
            {
                throw new Exception();
            }
        }
Beispiel #2
0
        public static List <TransferDetails> LoadTransferDetailsByID(string ID)
        {
            string strSql = "Select a.*,b.name,b.english_name" +
                            " FROM wm_TransferDetails a " +
                            " Left Join it_goods b ON a.GoodsID=b.id" +
                            " Where a.ID='" + ID + "'";

            strSql += " ORDER BY a.Seq Desc";
            DataTable dt = SQLHelper.ExecuteSqlReturnDataTable(strSql);
            List <TransferDetails> lsDetails = new List <TransferDetails>();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TransferDetails mdj = new TransferDetails();
                DataRow         dr  = dt.Rows[i];
                mdj.Seq         = dr["Seq"].ToString();
                mdj.ProductMo   = dr["ProductMo"].ToString();
                mdj.GoodsID     = dr["GoodsID"].ToString();
                mdj.LotNo       = dr["LotNo"].ToString();
                mdj.TransferQty = Convert.ToInt32(dr["TransferQty"]);
                mdj.QtyUnit     = dr["QtyUnit"].ToString();
                mdj.TransferWeg = Convert.ToDecimal(dr["TransferWeg"]);
                mdj.WegUnit     = dr["WegUnit"].ToString();
                mdj.GoodsName   = dr["name"].ToString();//"file:///"  + Server.MapPath("~")  +"~/Images/login.jpg";//
                mdj.NextLocID   = dr["NextLocID"].ToString();
                lsDetails.Add(mdj);
            }
            return(lsDetails);
        }
Beispiel #3
0
        public ActionResult <TransferDetails> Transfer(Transfer transfer)
        {
            decimal toAccountBalance   = accountDAO.GetAccount(transfer.AccountTo).Balance;
            decimal fromAccountBalance = accountDAO.GetAccount(transfer.AccountFrom).Balance;

            ActionResult result;


            if (fromAccountBalance < transfer.Amount)
            {
                result = BadRequest(new { message = "Aw, shucks. You've not enough bucks! Transfer failed. Next time better lucks!" });
            }

            else
            {
                decimal newToBalance     = toAccountBalance + transfer.Amount;
                bool    updateSuccessful = transferDAO.UpdateBalance(transfer.AccountTo, newToBalance);

                decimal newFromBalance = fromAccountBalance - transfer.Amount;
                updateSuccessful = transferDAO.UpdateBalance(transfer.AccountFrom, newFromBalance);

                if (updateSuccessful)
                {
                    TransferDetails added = transferDAO.CreateTransfer(transfer);
                    result = Created($"/transfer/{added.ID}", added);
                }
                else
                {
                    result = BadRequest(new { message = "Sorry, something didn't work. The transfer didn't work." });
                }
            }
            return(result);
        }
Beispiel #4
0
        public TransferDetails GetTransferDetails(int accountId, int transferId)
        {
            TransferDetails returnTransfer = null;

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();

                    SqlCommand cmd = new SqlCommand("SELECT transfer_id, transfer_type_desc, transfer_status_desc, username, amount FROM transfers " +
                                                    "join transfer_types on transfers.transfer_type_id = transfer_types.transfer_type_id " +
                                                    "join transfer_statuses on transfers.transfer_status_id = transfer_statuses.transfer_status_id " +
                                                    "join accounts on transfers.account_to = accounts.account_id " +
                                                    "join users on accounts.user_id = users.user_id " +
                                                    "WHERE transfer_id = @transferId and account_from = @accountId;", conn);

                    cmd.Parameters.AddWithValue("@transferId", transferId);
                    cmd.Parameters.AddWithValue("@accountId", accountId);
                    SqlDataReader reader = cmd.ExecuteReader();

                    if (reader.HasRows && reader.Read())
                    {
                        returnTransfer = GetTransferDeetsFromReader(reader);
                    }
                }
            }
            catch (SqlException)
            {
                throw;
            }

            return(returnTransfer);
        }
Beispiel #5
0
        public IActionResult UserHome(TransferDetails transferDetails)
        {
            ViewData["Balance"] = GetBalance();
            if (transferDetails.Amount != null)
            {
                var userData    = new UserDataAccessLayer();
                var FromAddress = LoginController.email;
                var ToAddress   = transferDetails.Address;
                var Amount      = decimal.Parse(transferDetails.Amount);
                var Type        = "transaction";
                var LoginStatus = userData.ValidateUserEmail(ToAddress);

                if (GetBalance() >= Amount && LoginStatus == "Success")
                {
                    using (WebSocket web = new WebSocket(url))
                    {
                        web.Connect();
                        web.Send(JsonConvert.SerializeObject(new { Type, FromAddress, ToAddress, Amount }));
                        Thread.Sleep(5000);
                        web.Close();
                    }
                }
                else
                {
                    TempData["UserEmailFailed"] = "The email you’ve entered doesn’t match any account";
                }
            }
            return(View());
        }
Beispiel #6
0
 public void IncludeFileDetails( FileInfo file )
 {
     Transfer = new TransferDetails
     {
         FileName = file.Name,
         FileSizeBytes = file.Length
     };
 }
 /// <summary>
 /// transferring patient from one ward to another
 /// </summary>
 /// <param name="transferData">transferring ward data</param>
 /// <param name="patDetails">previous ward data</param>
 public void TransferWardDac(TransferDetails transferData, Admission patDetails)
 {
     if (firebaseClient != null)
     {
         var result          = firebaseClient.Set("TransferList/" + Guid.NewGuid(), transferData);
         var updateAdmission = firebaseClient.Update("AdmissionList/" + transferData.NINumber, patDetails);
         UpdateWardAvailability(transferData.CurrentWard);
         TransferWardAvailability(transferData.PreviousWard);
     }
 }
Beispiel #8
0
 public void PrintTransferDetails(TransferDetails details)
 {
     Console.WriteLine("--------------------------------------------\n" +
                       "Transfer Details\n" +
                       "--------------------------------------------\n" +
                       $"Id: {details.ID}\n" +
                       $"From: {details.FromUser}\n" +
                       $"To: {details.ToUser}\n" +
                       $"Type: {details.Type}\n" +     // Send or Request
                       $"Status: {details.Status}\n" + // Pending, Approved, Rejected
                       $"Amount: ${details.Amount}");
 }
Beispiel #9
0
        public ActionResult AddList(TransferDetails model)
        {
            //listOrderInfo.Add(model);
            //var result = new { total = 100, rows = listOrderInfo };
            //return Json(result, JsonRequestBehavior.AllowGet);
            //model.ID = Request["ID"] == null ? "" : Request["ID"].ToString();
            //string FlagID = Request["FlagID"] == null ? "" : Request["FlagID"].ToString();
            //model.LocID=Request["LocID"] == null ? "" : Request["LocID"].ToString();
            //model.NextLocID = Request["NextLocID"] == null ? "" : Request["NextLocID"].ToString();
            var result = TransferDAL.UpdateTransferDetails(model);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public ActionResult <TransferDetails> GetTransfer(int accountId, int transferId)
        {
            TransferDetails transfer = transferDAO.GetTransferDetails(accountId, transferId);

            if (transfer == null || transfer.ID == 0)
            {
                return(NotFound(new { message = "No transfer was found with that Id" }));
            }
            else
            {
                return(transfer);
            }
        }
Beispiel #11
0
        private TransferDetails GetTransferDeetsFromReader(SqlDataReader reader)
        {
            TransferDetails tD = new TransferDetails()
            {
                ID     = Convert.ToInt32(reader["transfer_id"]),
                Type   = Convert.ToString(reader["transfer_type_desc"]),
                Status = Convert.ToString(reader["transfer_status_desc"]),
                ToUser = Convert.ToString(reader["username"]),
                Amount = Convert.ToDecimal(reader["amount"])
            };

            return(tD);
        }
Beispiel #12
0
        public void HistorcialTransfers(List <TransferHistory> transfers) // Used for menu option #2 // Still need to figure out return type.
        {
            // Do I need to check premission for spefic user's right to access transfers below?

            List <int> validID = new List <int>();

            // View your past transfers
            Console.WriteLine("-------------------------------------------\n" +
                              "Transfers\nID\t\t\tFrom/To\t\t\tAmount\n" +
                              "-------------------------------------------\n");
            foreach (TransferHistory transfer in transfers)
            {
                Console.WriteLine($"{transfer.TransferID}        {transfer.Direction}: {transfer.Username}      $ {transfer.Amount}");
                validID.Add(transfer.TransferID);
            }
            Console.WriteLine("---------\n" +
                              "Please enter transfer ID to view details (0 to cancel): ");
            // TransferHistory has TransferID, Username, Direction, & Amount
            //Transfer Details
            int subMenuSelection = -1;

            while (subMenuSelection != 0)
            {
                if (!int.TryParse(Console.ReadLine(), out subMenuSelection))
                {
                    Console.WriteLine("Invalid input. Please enter only a number.");
                }
                else if (validID.Contains(subMenuSelection))
                {
                    APIService      service = new APIService();
                    TransferDetails details = service.GetTransferDetails(subMenuSelection);
                    PrintTransferDetails(details);


                    //Show Transfer details
                    //Console.WriteLine("--------------------------------------------\n" +
                    //    "Transfer Details\n" +
                    //    "--------------------------------------------\n" +
                    //    $"Id: {details.ID}\n" +
                    //    $"From: {details.FromUser}\n" +
                    //    $"To: {details.ToUser}\n" +
                    //    $"Type: {details.Type}\n" + // Send or Request
                    //    $"Status: {details.Status}\n" + // Pending, Approved, Rejected
                    //    $"Amount: ${details.Amount}");
                }
                else if (subMenuSelection == 0)
                {
                    return;
                }
            }
        }
Beispiel #13
0
        private decimal GetBalance()
        {
            TransferDetails transferDetails = new TransferDetails();

            using (SqlConnection connection = new SqlConnection(UserDataAccessLayer.GetConnectionString()))
            {
                SqlCommand commandBalance = new SqlCommand("select dbo.ValidateUserEmail(@address)", connection);
                commandBalance.Parameters.Add("@address", SqlDbType.VarChar);
                commandBalance.Parameters["@address"].Value = LoginController.email;
                connection.Open();
                transferDetails.Balance = (decimal)commandBalance.ExecuteScalar();
            }
            return(transferDetails.Balance);
        }
Beispiel #14
0
        public void TransferFunds(TransferDetails transferDetails)
        {
            var sourceAccount      = dbContext.Balances.SingleOrDefault(b => b.CustomerId == transferDetails.From);
            var destinationAccount = dbContext.Balances.SingleOrDefault(b => b.CustomerId == transferDetails.To);

            if (sourceAccount != null && destinationAccount != null)
            {
                var transferableFunds = sourceAccount.Funds > transferDetails.Funds ? transferDetails.Funds : sourceAccount.Funds;
                sourceAccount.Funds      -= transferableFunds;
                destinationAccount.Funds += transferableFunds;

                dbContext.SaveChanges();

                logRepository.LogTransfer(transferDetails.From, transferDetails.To, transferableFunds);
            }
        }
Beispiel #15
0
        public ActionResult <TransferDetails> GetTransfer(int accountId, int transferId)
        {
            //Should I do this instead of NotFound?
            //IActionResult result = BadRequest(new { message = "Transfer ID not found" });

            TransferDetails transfer = transferDAO.GetTransferDetails(accountId, transferId);

            if (transfer == null || transfer.ID == 0)
            {
                return(NotFound(new { message = "No transfer was found with that Id" }));
            }
            else
            {
                return(transfer);
            }
        }
Beispiel #16
0
        public static List <TransferDetails> SearchTransfer(QueryTransferParas model)
        {
            string strSql = "Select a.TransferDate,b.*,c.name,c.english_name" +
                            " FROM wm_TransferHead a " +
                            " Inner Join wm_TransferDetails b On a.ID=b.ID" +
                            " Left Join it_goods c ON b.GoodsID=c.id" +
                            " Where a.ID>='" + "" + "'";

            if (model.IDFrom != null && model.IDTo != null)
            {
                strSql += " And a.ID>='" + model.IDFrom + "' And a.ID<='" + model.IDTo + "'";
            }
            if (model.TransferDateFrom != null && model.TransferDateTo != null)
            {
                string DateTo = Convert.ToDateTime(model.TransferDateTo).AddDays(1).ToString("yyyy/MM/dd");
                strSql += " And a.TransferDate>='" + model.TransferDateFrom + "' And a.TransferDate<'" + DateTo + "'";
            }
            if (model.IDFrom == null && model.IDTo == null && model.TransferDateFrom == null && model.TransferDateTo == null)
            {
                strSql += " And a.ID=''";
            }
            strSql += " ORDER BY a.TransferDate Desc,b.Seq Desc";
            DataTable dt = SQLHelper.ExecuteSqlReturnDataTable(strSql);
            List <TransferDetails> lsDetails = new List <TransferDetails>();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TransferDetails mdj = new TransferDetails();
                DataRow         dr  = dt.Rows[i];
                mdj.TransferDate = dr["TransferDate"].ToString();
                mdj.ID           = dr["ID"].ToString();
                mdj.Seq          = dr["Seq"].ToString();
                mdj.ProductMo    = dr["ProductMo"].ToString();
                mdj.GoodsID      = dr["GoodsID"].ToString();
                mdj.LotNo        = dr["LotNo"].ToString();
                mdj.TransferQty  = Convert.ToInt32(dr["TransferQty"]);
                mdj.QtyUnit      = dr["QtyUnit"].ToString();
                mdj.TransferWeg  = Convert.ToDecimal(dr["TransferWeg"]);
                mdj.WegUnit      = dr["WegUnit"].ToString();
                mdj.GoodsName    = dr["name"].ToString();//"file:///"  + Server.MapPath("~")  +"~/Images/login.jpg";//
                mdj.NextLocID    = dr["NextLocID"].ToString();
                lsDetails.Add(mdj);
            }
            return(lsDetails);
        }
Beispiel #17
0
        /// <summary>
        /// Implementaion class for patients ward transfer
        /// </summary>
        /// <returns>true or false</returns>
        public void TransferWard()
        {
            //Console.WriteLine("Transfer Ward");
            TransferDetails transferData = new TransferDetails();

            Console.WriteLine("Patient NHS Number:");
            transferData.NINumber = Console.ReadLine();

            var patDetails = _patientsDac.GetPatient(transferData.NINumber);

            if (patDetails != null && patDetails.Status)
            {
                Console.WriteLine("Transfer Ward Type(1.Cardiology 2.Renal 3.A&E 4.Critical Care):");
                transferData.CurrentWard = Console.ReadLine();
                Console.WriteLine("Doctor Assigned");
                transferData.CurrentDoctor = Console.ReadLine();
                transferData.Date          = DateTime.Now;

                if (patDetails.WardType == transferData.CurrentWard)
                {
                    Console.WriteLine("Cannot transfer within same ward");
                }
                else
                {
                    transferData.PreviousDoctor = patDetails.DoctorId;
                    transferData.PreviousWard   = patDetails.WardType;
                    WardDetails wDetails = _patientsDac.GetAvailability(transferData.CurrentWard);
                    if (wDetails != null && wDetails.AvailableBed != 0)
                    {
                        patDetails.WardType = transferData.CurrentWard;
                        patDetails.DoctorId = transferData.CurrentDoctor;
                        _patientsDac.TransferWardDac(transferData, patDetails);
                        Console.WriteLine("Patient transferred to new ward!!!");
                    }
                    else
                    {
                        Console.WriteLine("There is no Bed availablility in this ward!!!");
                    }
                }
            }
            else
            {
                Console.WriteLine("Patient Record Not Found!!!");
            }
        }
Beispiel #18
0
        public IEnumerable <IResult> EditPosting(PostingRecord transactionRecord)
        {
            if (transactionRecord.Journal is TransactionDTO)
            {
                TransactionDetails.Edit(transactionRecord.Journal as TransactionDTO, AccountId);
                ActivateItem(TransactionDetails);
            }
            else if (transactionRecord.Journal is TransferDTO)
            {
                var transferResult = new GetPostingResult(AccountId, transactionRecord.TransactionId, eventAggregator);
                yield return(transferResult);

                var transfer = transferResult.Transaction as TransferDTO;
                TransferDetails.Edit(transfer, AccountId);
                ActivateItem(TransferDetails);
            }
            else
            {
                throw new NotSupportedException(string.Format("Transaction of type {0} is not editable.", transactionRecord.Journal.GetType()));
            }
        }
        public void GetTransfer(int accountID, int transferID)
        {
            if (client.Authenticator == null)
            {
                client.Authenticator = new JwtAuthenticator(UserService.GetToken());
            }

            RestRequest request = new RestRequest(API_BASE_URL + "transfer/" + accountID + "/" + transferID);
            IRestResponse <TransferDetails> response = client.Get <TransferDetails>(request);

            if (response.ResponseStatus != ResponseStatus.Completed)
            {
                Console.WriteLine("An error occurred communicating with the server.");
            }
            else if (!response.IsSuccessful)
            {
                if (!string.IsNullOrWhiteSpace(response.Data.Message))
                {
                    Console.WriteLine("An error message was received: " + response.Data.Message);
                }
                else
                {
                    Console.WriteLine("An error response was received from the server. The status code is " + (int)response.StatusCode);
                }
            }

            else
            {
                TransferDetails t = response.Data;

                Console.WriteLine($"\n------------------------------------------");
                Console.WriteLine("Transfer Details \n------------------------------------------");
                Console.WriteLine($"Id: {t.ID}");
                Console.WriteLine($"From:  {UserService.GetUserName()}");
                Console.WriteLine($"To:  {t.ToUser}");
                Console.WriteLine($"Type:  {t.Type}");
                Console.WriteLine($"Status:  {t.Status}");
                Console.WriteLine($"Amount:  {t.Amount}");
            }
        }
Beispiel #20
0
        public TransferDetails GetTransferDetails(int transID = 0, Transfer transfer = null) // this will allow a parameterless method call
        {
            TransferDetails details = new TransferDetails();

            if (transID != 0)
            {
                transfer = transferDAO.GetTransferDetails(transID);
            }

            string senderName   = GetUserName(transfer.FromUserID);
            string receiverName = GetUserName(transfer.ToUserID);

            details.ID       = transfer.ID;
            details.FromUser = senderName;
            details.ToUser   = receiverName;
            details.Type     = transfer.Type;
            details.Status   = transfer.Status;
            details.Amount   = transfer.Amount;


            return(details);
        }
Beispiel #21
0
        public List <TransferDetails> GetTransfers(int fromAccount)
        {
            List <TransferDetails> transfers = new List <TransferDetails>();

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();

                    SqlCommand cmd = new SqlCommand("SELECT transfer_id, transfer_type_desc, transfer_status_desc, username, amount FROM transfers " +
                                                    "join transfer_types on transfers.transfer_type_id = transfer_types.transfer_type_id " +
                                                    "join transfer_statuses on transfers.transfer_status_id = transfer_statuses.transfer_status_id " +
                                                    "join accounts on transfers.account_to = accounts.account_id " +
                                                    "join users on accounts.user_id = users.user_id " +
                                                    "WHERE account_from = @fromId OR account_to = @fromId;", conn);

                    cmd.Parameters.AddWithValue("@fromId", $"{fromAccount}");
                    SqlDataReader reader = cmd.ExecuteReader();


                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            TransferDetails transfer = GetTransferDeetsFromReader(reader);
                            transfers.Add(transfer);
                        }
                    }
                }
            }
            catch (SqlException)
            {
                throw;
            }
            return(transfers);
        }
Beispiel #22
0
        private MenuOptionResult ViewTransfers()
        {
            List <Transfer> userTransfers = apiService.GetUserTransfers();

            Console.WriteLine("Transfer History");
            Console.WriteLine("-------------------------------------------");
            foreach (Transfer tran in userTransfers)
            {
                if (tran.AccountFrom == UserService.GetUserId())
                {
                    Console.WriteLine($"Transfer ID:{tran.TransferId}\tTo:{tran.UsernameTo}\tAmount:{tran.Amount:C}");
                }
                else if (tran.AccountTo == UserService.GetUserId())
                {
                    Console.WriteLine($"Transfer ID:{tran.TransferId}\tFrom:{tran.UsernameFrom}\tAmount:{tran.Amount:C}");
                }
            }
            Console.WriteLine("-------------------------------------------");
            Console.Write("Please enter Transfer ID to view more details: ");

            Int32.TryParse(Console.ReadLine(), out int toTransferId);
            TransferDetails details = apiService.GetTransferDetails(toTransferId);

            Console.WriteLine("-------------------------------------------");
            Console.WriteLine("Transfer Details");
            Console.WriteLine("-------------------------------------------\n");
            Console.WriteLine($"Id: {details.Id}");
            Console.WriteLine($"Account from: {details.From}");
            Console.WriteLine($"Account to: {details.To}");
            Console.WriteLine($"Type: {details.Type}");
            Console.WriteLine($"Status: {details.Status}");
            Console.WriteLine($"Amount: {details.Amount:C}\n");
            Console.WriteLine("-------------------------------------------");
            Console.WriteLine("Please press any key to return to the Main Menu");
            return(MenuOptionResult.WaitAfterMenuSelection);
        }
Beispiel #23
0
 /// <summary>
 /// Open dialog for creating new transfer.
 /// </summary>
 public void NewTransfer()
 {
     TransferDetails.Create(AccountId, startDate.Date);
     ActivateItem(TransferDetails);
 }
    //public static Double v1out, vedvout;
    //public static Vector3d oVel;

    /// <summary>
    /// Find the delta-v required for a ballistic transfer from <paramref name="origin"/> to <paramref name="destination"/>,
    /// departing at <paramref name="ut"/> UT, with a time of flight of <paramref name="dt"/> seconds, starting from a circular
    /// parking orbit <paramref name="initialOrbitAltitude"/> meters above the origin's surface, and optionally inserting into a
    /// final orbit <paramref name="finalOrbitAltitude"/> meters above the destination's surface.
    /// </summary>
    /// <returns>The total delta-v in meters per second of the specified transfer.</returns>
    /// <param name="origin">The origin body.</param>
    /// <param name="destination">The destination body. Must have the same <c>referenceBody</c> as <paramref name="origin"/>.</param>
    /// <param name="ut">The universal time of departure, in seconds. Must be greater than 0.</param>
    /// <param name="dt">The time of flight, in seconds. Must be greater than 0.</param>
    /// <param name="initialOrbitAltitude">The altitude of the initial circular parking orbit. If 0, parking orbit ejection is ignored. Must be greater than or equal to 0.</param>
    /// <param name="finalOrbitAltitude">(Optional) The altitude of the final circular orbit. Must be greater than or equal to 0 if provided.</param>
    /// <param name="oTransfer">Output object that contains all the basic details of the calculated transfer</param>
    public static double TransferDeltaV(CelestialBody origin, CelestialBody destination, double ut, double dt, double initialOrbitAltitude, double?finalOrbitAltitude, out TransferDetails oTransfer)
    {
        double   gravParameter             = origin.referenceBody.gravParameter;
        double   tA                        = origin.orbit.TrueAnomalyAtUT(ut);
        Vector3d originPositionAtDeparture = OrbitPositionFromTrueAnomaly(origin.orbit, tA);
        Vector3d originVelocity            = OrbitVelocityFromTrueAnomaly(origin.orbit, tA);

        //oVel = originVelocity;

        tA = destination.orbit.TrueAnomalyAtUT(ut + dt);
        Vector3d destinationPositionAtArrival = OrbitPositionFromTrueAnomaly(destination.orbit, tA);

        bool longWay = Vector3d.Cross(originPositionAtDeparture, destinationPositionAtArrival).z < 0;

        Vector3d velocityBeforeInsertion;
        Vector3d velocityAfterEjection = Solve(gravParameter, originPositionAtDeparture, destinationPositionAtArrival, dt, longWay, out velocityBeforeInsertion);

        Vector3d ejectionDeltaVector = velocityAfterEjection - originVelocity;
        double   ejectionInclination = 0, vesselOriginOrbitalSpeed = 0;   //Extra variables for Transfer Details
        double   ejectionDeltaV = ejectionDeltaVector.magnitude;

        if (initialOrbitAltitude > 0)
        {
            double mu   = origin.gravParameter;
            double r0   = initialOrbitAltitude + origin.Radius;
            double rsoi = origin.sphereOfInfluence;
            double v0   = Math.Sqrt(origin.gravParameter / r0);                                     // Initial circular orbit velocity
            double v1   = Math.Sqrt(ejectionDeltaV * ejectionDeltaV + 2 * v0 * v0 - 2 * mu / rsoi); // Velocity at periapsis

            //v1out = v1; vedvout = ejectionDeltaV;

            vesselOriginOrbitalSpeed = v0;      //Store this for later

            double e  = r0 * v1 * v1 / mu - 1;  // Ejection orbit eccentricity
            double ap = r0 * (1 + e) / (1 - e); // Ejection orbit apoapsis

            if (ap > 0 && ap <= rsoi)
            {
                oTransfer = null;   //Nuke this if we have no result
                return(Double.NaN); // There is no orbit that leaves the SoI with a velocity of ejectionDeltaV
            }

            if (ejectionDeltaVector.z != 0)
            {
                double sinEjectionInclination = ejectionDeltaVector.z / ejectionDeltaV;
                ejectionInclination = Math.Asin(sinEjectionInclination);    //Store this for later
                ejectionDeltaV      = Math.Sqrt(v0 * v0 + v1 * v1 - 2 * v0 * v1 * Math.Sqrt(1 - sinEjectionInclination * sinEjectionInclination));
            }
            else
            {
                ejectionDeltaV = v1 - v0;
            }
        }

        //Create a transfer object and set all the details we have
        oTransfer = new TransferDetails(origin, destination, ut, dt);
        oTransfer.OriginVesselOrbitalSpeed = vesselOriginOrbitalSpeed;
        oTransfer.OriginVelocity           = originVelocity;
        oTransfer.TransferInitalVelocity   = velocityAfterEjection;
        oTransfer.TransferFinalVelocity    = velocityBeforeInsertion;
        oTransfer.TransferAngle            = Math.Acos(Vector3d.Dot(originPositionAtDeparture, destinationPositionAtArrival) / (originPositionAtDeparture.magnitude * destinationPositionAtArrival.magnitude));
        oTransfer.EjectionDeltaVector      = ejectionDeltaVector;
        //reset the magnitude of the ejectionDeltaV to take into account the orbital velocity of the craft
        oTransfer.EjectionDeltaVector = oTransfer.EjectionDeltaVector.normalized * ejectionDeltaV;
        oTransfer.EjectionInclination = ejectionInclination;

        double insertionDeltaV = 0;
        double insertionInclination = 0, vesselDestinationOrbitalSpeed = 0;     //Extra variables for Transfer Details

        if (finalOrbitAltitude.HasValue)
        {
            Vector3d destinationVelocity = OrbitVelocityFromTrueAnomaly(destination.orbit, tA);

            //Tweak this bit so we have the vector and inclination values for use later
            Vector3d insertionDeltaVector = velocityBeforeInsertion - destinationVelocity;
            insertionDeltaV = insertionDeltaVector.magnitude;
            if (insertionDeltaVector.z != 0)
            {
                insertionInclination = Math.Asin(insertionDeltaVector.z / insertionDeltaV);
            }

            if (finalOrbitAltitude.Value != 0)
            {
                double finalOrbitVelocity = Math.Sqrt(destination.gravParameter / (finalOrbitAltitude.Value + destination.Radius));
                vesselDestinationOrbitalSpeed = finalOrbitVelocity;                      //Store this for later
                insertionDeltaV = Math.Sqrt(insertionDeltaV * insertionDeltaV + 2 * finalOrbitVelocity * finalOrbitVelocity - 2 * destination.gravParameter / destination.sphereOfInfluence) - finalOrbitVelocity;

                //Store away the extra details about the Destination/Injection
                oTransfer.DestinationVesselOrbitalSpeed = vesselDestinationOrbitalSpeed;
                oTransfer.DestinationVelocity           = destinationVelocity;
                //oTransfer.InjectionDeltaVector = (velocityBeforeInsertion - destinationVelocity);
                oTransfer.InjectionDeltaVector = oTransfer.EjectionDeltaVector.normalized * insertionDeltaV;
                oTransfer.InsertionInclination = insertionInclination;
            }
            else
            {
                //This is a flyby so there is no injection burn
                //Store away the extra details about the Destination/Injection
                oTransfer.DestinationVesselOrbitalSpeed = velocityBeforeInsertion.magnitude;
                oTransfer.DestinationVelocity           = destinationVelocity;
                oTransfer.InjectionDeltaVector          = new Vector3d();
                oTransfer.InsertionInclination          = 0;
            }
        }

        return(oTransfer.DVTotal); //ejectionDeltaV + insertionDeltaV;
    }
Beispiel #25
0
        public ActionResult <TransferDetails> GetTransfer(int transferId)
        {
            TransferDetails details = transferDAO.GetTransferDetails(transferId);

            return(Ok(details));
        }
Beispiel #26
0
        public static UpdateStatusModels UpdateTransferDetails(TransferDetails model)
        {
            string             result    = "";
            bool               ValidFlag = true;
            string             strSql    = "";
            string             ID        = model.ID;
            string             LocID     = model.LocID;
            string             NextLocID = model.NextLocID;
            string             QtyUnit   = model.QtyUnit;
            string             WegUnit   = model.WegUnit;
            UpdateStatusModels resModel  = new UpdateStatusModels();
            DataTable          dtFlag    = BaseDataDAL.GetDocFlayReturnTable("wh_transfer", model.FlagID);
            string             flag0     = dtFlag.Rows[0]["flag0"].ToString().Trim();
            string             flag1     = dtFlag.Rows[0]["flag1"].ToString().Trim();
            string             flag2     = dtFlag.Rows[0]["flag2"].ToString().Trim();

            strSql += string.Format(@" SET XACT_ABORT  ON ");
            strSql += string.Format(@" BEGIN TRANSACTION ");
            bool FirstRec = false;

            if (ID == null || ID == "")
            {
                FirstRec = true;
                ID       = GenNumberDAL.GenTransferID(flag0, LocID, NextLocID, flag2);
            }
            else
            {
                if (!CheckTransferHead(ID))
                {
                    FirstRec = true;
                    ID       = GenNumberDAL.GenTransferID(flag0, LocID, NextLocID, flag2);
                }
            }
            if (FirstRec)
            {
                strSql += string.Format(@"Insert Into wm_TransferHead (ID,TransferDate,LocID,NextLocID,FlagID) Values ('"
                                        + ID + "','" + model.TransferDate + "','" + model.LocID + "','" + model.NextLocID + "','" + model.FlagID + "')");
            }
            else
            {
                strSql += string.Format(@"UPDATE wm_TransferHead SET TransferDate='{0}' WHERE ID='{1}'"
                                        , model.TransferDate, ID);
            }

            string  ProductMo = model.ProductMo;
            string  GoodsID   = model.GoodsID;
            string  LotNo     = model.LotNo;
            decimal Qty       = model.TransferQty.ToString().Trim() != "" ? model.TransferQty : 0;
            decimal Weg       = model.TransferWeg.ToString().Trim() != "" ? model.TransferWeg : 0;

            result = CheckQtyStore(LocID, GoodsID, ProductMo, LotNo, flag1, Weg, Qty);
            if (result != "")
            {
                ValidFlag = false;
            }
            else
            {
                if (flag2 == "TO")
                {
                    result = CheckQtyStore(NextLocID, GoodsID, ProductMo, LotNo, "+", Weg, Qty);
                    if (result != "")
                    {
                        ValidFlag = false;
                    }
                }
            }
            if (ValidFlag == false)
            {
                resModel.Msg = result;
                return(resModel);
            }

            string Seq        = GenNumberDAL.GetDetailsSeq("wm_TransferDetails", model.ID);
            string CreateUser = "";
            string CreateTime = System.DateTime.Now.ToString("yyyy/MM/dd HH:ss:mm");

            strSql += string.Format(@"Insert Into wm_TransferDetails (ID,Seq,ProductMo,GoodsID,LocID,LotNo,TransferQty,TransferWeg,QtyUnit,WegUnit,NextLocID,CreateUser,CreateTime) Values " +
                                    "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}')"
                                    , ID, Seq, model.ProductMo, model.GoodsID, model.LocID, model.LotNo, model.TransferQty, model.TransferWeg, QtyUnit, WegUnit, NextLocID, "", CreateTime);
            strSql += string.Format(JoinUpdateStr("U", LocID, GoodsID, ProductMo, LotNo, flag1, Weg, Qty, CreateUser, CreateTime));
            if (flag2 == "TO")
            {
                strSql += string.Format(JoinUpdateStr("U", NextLocID, GoodsID, ProductMo, LotNo, "+", Weg, Qty, CreateUser, CreateTime));
            }
            strSql += string.Format(@" COMMIT TRANSACTION ");
            result  = SQLHelper.ExecuteSqlUpdate(strSql);
            if (result == "")
            {
                resModel.Status = "OK";
            }
            else
            {
                resModel.Status = "ERROR";
                resModel.Msg    = result;
            }
            resModel.ReturnValue = ID;
            return(resModel);
        }
Beispiel #27
0
        //public Transfer UpdateRejectedTransfer(int transferId)
        //{
        //    string sql = @"Update transfers
        //                        Set transfers.transfer_status_id = 3
        //                                Where transfer_id = @transferId";
        //    Transfer tran = new Transfer();
        //    try
        //    {
        //        using (SqlConnection conn = new SqlConnection(connString))
        //        {
        //            conn.Open();

        //            SqlCommand cmd = new SqlCommand(sql, conn);
        //            cmd.Parameters.AddWithValue("@transferId", transferId);

        //            int rowsAffected = cmd.ExecuteNonQuery();
        //            SqlDataReader rdr = cmd.ExecuteReader();
        //            while (rdr.Read())
        //            {
        //                tran.TransferId = Convert.ToInt32(rdr["transfer_id"]);
        //                tran.TransferTypeId = Convert.ToInt32(rdr["transfer_type_id"]);
        //                tran.TransferStatusId = Convert.ToInt32(rdr["transfer_status_id"]);
        //                tran.AccountFrom = Convert.ToInt32(rdr["account_from"]);
        //                tran.AccountTo = Convert.ToInt32(rdr["account_to"]);
        //                tran.Amount = Convert.ToDecimal(rdr["amount"]);
        //            }
        //        }
        //        return tran;
        //    }
        //    catch (SqlException ex)
        //    {
        //        Console.WriteLine(ex.Message);
        //        throw;
        //    }
        //}

        public TransferDetails GetTransferDetails(int transferId)
        {
            string          sql     = @"Select transfers.*, users.username as usernameFrom,
                        (Select username from users where transfers.account_to = users.user_id) as usernameTo from transfers
                            join accounts on accounts.user_id = transfers.account_from
                                join users on accounts.user_id = users.user_id
                                    where transfers.transfer_id = @transferId";
            Transfer        tran    = new Transfer();
            TransferDetails details = new TransferDetails();

            try
            {
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    conn.Open();

                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@transferId", transferId);

                    SqlDataReader rdr = cmd.ExecuteReader();

                    while (rdr.Read())
                    {
                        tran.TransferId       = Convert.ToInt32(rdr["transfer_id"]);
                        tran.TransferTypeId   = Convert.ToInt32(rdr["transfer_type_id"]);
                        tran.TransferStatusId = Convert.ToInt32(rdr["transfer_status_id"]);
                        details.From          = Convert.ToString(rdr["usernameFrom"]);
                        details.To            = Convert.ToString(rdr["usernameTo"]);
                        tran.Amount           = Convert.ToDecimal(rdr["amount"]);
                    }

                    details.Id     = tran.TransferId;
                    details.Amount = tran.Amount;

                    if (tran.TransferTypeId == 1)
                    {
                        details.Type = "Request";
                    }
                    else
                    {
                        details.Type = "Send";
                    }
                    if (tran.TransferStatusId == 1)
                    {
                        details.Status = "Pending";
                    }
                    else if (tran.TransferStatusId == 2)
                    {
                        details.Status = "Approved";
                    }
                    else
                    {
                        details.Status = "Rejected";
                    }

                    return(details);
                }
            }
            catch (SqlException ex)
            {
                throw;
            }
        }
 /// <summary>
 /// Transfers funds between two customers
 /// </summary>
 /// <param name="transferDetails">Details about the transfer</param>
 public void TransferFunds(TransferDetails transferDetails)
 {
     Repository.TransferFunds(transferDetails);
 }
Beispiel #29
0
        private static void MenuSelection()
        {
            int menuSelection = -1;

            while (menuSelection != 0)
            {
                Console.WriteLine("");
                Console.WriteLine("Welcome to TEnmo! Please make a selection: ");
                Console.WriteLine("1: View your current balance");
                Console.WriteLine("2: View your past transfers");
                Console.WriteLine("3: View your pending requests");
                Console.WriteLine("4: Send TE bucks");
                Console.WriteLine("5: Request TE bucks");
                Console.WriteLine("6: Log in as different user");
                Console.WriteLine("0: Exit");
                Console.WriteLine("---------");
                Console.Write("Please choose an option: ");

                if (!int.TryParse(Console.ReadLine(), out menuSelection))
                {
                    Console.WriteLine("Invalid input. Please enter only a number.");
                }
                else if (menuSelection == 1)
                {
                    //Console.WriteLine(UserService.GetToken());
                    Console.Write("Your current account balance is: $");
                    Console.WriteLine(accountService.GetBalanceOfAccount(UserService.GetUserId()));

                    //Console.WriteLine(user.GetUserId());
                }
                else if (menuSelection == 2)
                {
                    int accountId = UserService.GetUserId();
                    List <TransferDetails> transfers = transferService.GetTransfers(accountId);
                    Console.WriteLine($"\n\nWhere did my money go? \nWe would all like to know. \nNow you can view below \nhow your dough got so low:");
                    Console.WriteLine($"------------------------------------------");
                    Console.WriteLine("\nTransfers \nID        From/To        Amount");
                    Console.WriteLine($"------------------------------------------");
                    foreach (TransferDetails tD in transfers)
                    {
                        Console.WriteLine($"{tD.ID}".PadRight(10) + $"To:  {tD.ToUser}".PadRight(17) + $"$ {tD.Amount}");
                    }
                    Console.WriteLine("\nWhat do IDs like to chase?... (press enter or you will never know)");
                    string nothing = Console.ReadLine();
                    Console.WriteLine("Their IDetails!\n... . . . . .  .  .  .   .   .   ");
                    Console.WriteLine("\nTo view the details from a transfer enter the ID number. To return to the main menu press 0.");
                    int userInput = int.Parse(Console.ReadLine());
                    if (userInput > 0)
                    {
                        transferService.GetTransfer(accountId, userInput);
                    }
                    else
                    {
                        Console.WriteLine("Sorry, that's not a valid transfer ID");
                    }
                }

                else if (menuSelection == 3)
                {
                }


                else if (menuSelection == 4)
                {
                    Console.WriteLine("Here is a list of Users and Ids available to send TEnmo Bucks to: ");
                    transferService.GetUsers();
                    Transfer transferAttempt = consoleService.PromptForTransferData();

                    if (transferAttempt == null || !transferAttempt.IsValid)
                    {
                        Console.WriteLine("Transfer failed - incorrect data entered.");
                    }

                    else
                    {
                        TransferDetails completedTransfer = transferService.TransferRequest(transferAttempt);
                        if (completedTransfer != null)
                        {
                            Console.WriteLine("Transfer successful.");
                            Console.WriteLine($"Transfer details: {completedTransfer.ToUser}, {completedTransfer.Amount} ");
                        }
                        else
                        {
                            Console.WriteLine("Transfer failed.");
                        }
                    }
                }


                else if (menuSelection == 5)
                {
                }


                else if (menuSelection == 6)
                {
                    Console.WriteLine("");
                    UserService.SetLogin(new API_User()); //wipe out previous login info
                    Run();                                //return to entry point
                }

                else
                {
                    Console.WriteLine("Ok, come back with more munny soon!");
                    Environment.Exit(0);
                }
            }
        }
Beispiel #30
0
        public static PostHandler ChainPostHandlers(PostHandler baseHandler, Report report, bool forAccountsReport = false)
        {
            PostHandler        handler          = baseHandler;
            Predicate          displayPredicate = null;
            Predicate          onlyPredicate    = null;
            DisplayFilterPosts displayFilter    = null;

            Expr expr = report.AmountHandler.Expr;

            expr.Context = report;

            report.TotalHandler.Expr.Context         = report;
            report.DisplayAmountHandler.Expr.Context = report;
            report.DisplayTotalHandler.Expr.Context  = report;

            if (!forAccountsReport)
            {
                // Make sure only forecast postings which match are allowed through
                if (report.ForecastWhileHandler.Handled)
                {
                    handler = new FilterPosts(handler, new Predicate(report.ForecastWhileHandler.Str(), report.WhatToKeep()), report);
                }

                // truncate_xacts cuts off a certain number of _xacts_ from being
                // displayed.  It does not affect calculation.
                if (report.HeadHandler.Handled || report.TailHandler.Handled)
                {
                    handler = new TruncateXacts(handler,
                                                report.HeadHandler.Handled ? Int32.Parse(report.HeadHandler.Value) : 0,
                                                report.TailHandler.Handled ? Int32.Parse(report.TailHandler.Value) : 0);
                }

                // display_filter_posts adds virtual posts to the list to account
                // for changes in value of commodities, which otherwise would affect
                // the running total unpredictably.
                handler = displayFilter = new DisplayFilterPosts(handler, report, report.RevaluedHandler.Handled && !report.NoRoundingHandler.Handled);

                // filter_posts will only pass through posts matching the
                // `display_predicate'.
                if (report.DisplayHandler.Handled)
                {
                    displayPredicate = new Predicate(report.DisplayHandler.Str(), report.WhatToKeep());
                    handler          = new FilterPosts(handler, displayPredicate, report);
                }
            }

            // changed_value_posts adds virtual posts to the list to account for changes
            // in market value of commodities, which otherwise would affect the running
            // total unpredictably.
            if (report.RevaluedHandler.Handled && (!forAccountsReport || report.UnrealizedHandler.Handled))
            {
                handler = new ChangedValuePost(handler, report, forAccountsReport, report.UnrealizedHandler.Handled, displayFilter);
            }

            // calc_posts computes the running total.  When this appears will determine,
            // for example, whether filtered posts are included or excluded from the
            // running total.
            handler = new CalcPosts(handler, expr, !forAccountsReport || (report.RevaluedHandler.Handled && report.UnrealizedHandler.Handled));

            // filter_posts will only pass through posts matching the
            // `secondary_predicate'.
            if (report.OnlyHandler.Handled)
            {
                onlyPredicate = new Predicate(report.OnlyHandler.Str(), report.WhatToKeep());
                handler       = new FilterPosts(handler, onlyPredicate, report);
            }

            if (!forAccountsReport)
            {
                // sort_posts will sort all the posts it sees, based on the `sort_order'
                // value expression.
                if (report.SortHandler.Handled)
                {
                    if (report.SortXactsHandler.Handled)
                    {
                        handler = new SortXacts(handler, new Expr(report.SortHandler.Str()), report);
                    }
                    else
                    {
                        handler = new SortPosts(handler, report.SortHandler.Str(), report);
                    }
                }

                // collapse_posts causes xacts with multiple posts to appear as xacts
                // with a subtotaled post for each commodity used.
                if (report.CollapseHandler.Handled)
                {
                    handler = new CollapsePosts(handler, report, expr, displayPredicate, onlyPredicate, report.CollapseIfZeroHandler.Handled);
                }

                // subtotal_posts combines all the posts it receives into one subtotal
                // xact, which has one post for each commodity in each account.
                //
                // period_posts is like subtotal_posts, but it subtotals according to time
                // periods rather than totalling everything.
                //
                // day_of_week_posts is like period_posts, except that it reports
                // all the posts that fall on each subsequent day of the week.
                if (report.EquityHandler.Handled)
                {
                    handler = new PostsAsEquity(handler, report, expr);
                }
                else if (report.SubTotalHandler.Handled)
                {
                    handler = new SubtotalPosts(handler, expr);
                }
            }

            if (report.DowHandler.Handled)
            {
                handler = new DayOfWeekPosts(handler, expr);
            }
            else if (report.ByPayeeHandler.Handled)
            {
                handler = new ByPayeePosts(handler, expr);
            }

            // interval_posts groups posts together based on a time period, such as
            // weekly or monthly.
            if (report.PeriodHandler.Handled)
            {
                handler = new IntervalPosts(handler, expr, new DateInterval(report.PeriodHandler.Str()), report.ExactHandler.Handled, report.EmptyHandler.Handled);
            }

            if (report.DateHandler.Handled)
            {
                handler = new TransferDetails(handler, TransferDetailsElementEnum.SET_DATE, report.Session.Journal.Master, new Expr(report.DateHandler.Str()), report);
            }

            if (report.AccountHandler.Handled)
            {
                handler = new TransferDetails(handler, TransferDetailsElementEnum.SET_ACCOUNT, report.Session.Journal.Master, new Expr(report.AccountHandler.Str()), report);
            }
            else if (report.PivotHandler.Handled)
            {
                string pivot = string.Format("\"{0}:\" + tag(\"{0}\")", report.PivotHandler.Str());
                handler = new TransferDetails(handler, TransferDetailsElementEnum.SET_ACCOUNT, report.Session.Journal.Master, new Expr(pivot), report);
            }

            if (report.PayeeHandler.Handled)
            {
                handler = new TransferDetails(handler, TransferDetailsElementEnum.SET_PAYEE, report.Session.Journal.Master, new Expr(report.PayeeHandler.Str()), report);
            }

            // related_posts will pass along all posts related to the post received.  If
            // the `related_all' handler is on, then all the xact's posts are passed;
            // meaning that if one post of an xact is to be printed, all the post for
            // that xact will be printed.
            if (report.RelatedHandler.Handled)
            {
                handler = new RelatedPosts(handler, report.RelatedAllHandler.Handled);
            }

            if (report.InjectHandler.Handled)
            {
                handler = new InjectPosts(handler, report.InjectHandler.Str(), report.Session.Journal.Master);
            }

            return(handler);
        }
        /// <summary>
        /// Transfers funds between two customers
        /// </summary>
        /// <param name="transferDetails">Details about the transfer</param>
        public void TransferFunds(TransferDetails transferDetails)
        {
            var availableFunds = WithdrawFromAvailableFunds(transferDetails.From, transferDetails.Funds);

            DepositFunds(transferDetails.To, availableFunds);
        }