Пример #1
0
        static List <Money> GetExpenses(string dateFrom, string dateTo, IQueryable <Cashflow> cashflows, string prefix, TraceWriter log)
        {
            var dateFromInverted = $"{prefix}_{RowKeyUtils.ConvertInvertedDateToDateFrom(RowKeyUtils.InvertDateString(dateFrom))}";
            var dateToInverted   = $"{prefix}_{RowKeyUtils.ConvertInvertedDateToDateTo(RowKeyUtils.InvertDateString(dateTo))}";

            log.Info($"GetCashSummary: getting expenses with prefix: {prefix} from date {dateFromInverted} to date {dateToInverted}");

            var list = cashflows
                       .Where(x => x.RowKey.CompareTo(dateFromInverted) < 0)
                       .Where(x => x.RowKey.CompareTo(dateToInverted) > 0)
                       .ToList();

            log.Info($"GetCashSummary: for prefix {prefix} found {list.Count} rows.");

            var result = list
                         .Select(x => JsonConvert.DeserializeObject <Money>(x.Amount))
                         .GroupBy(x => x.Currency, x => x.Amount, (x, y) => new Money()
            {
                Currency = x, Amount = y.Sum()
            })
                         .ToList();

            log.Info($"GetCashSummary: for prefix {prefix} result contains {result.Count} rows.");

            return(result);
        }
Пример #2
0
        public void GetInvertedDateString_IsInverseFunctionOf_GetInvertedDateTime()
        {
            var dateString = "1234.12.03_01:02:03";

            var invertedDateTime   = RowKeyUtils.GetInvertedDateTime(dateString);
            var invertedDateString = RowKeyUtils.GetInvertedDateString(invertedDateTime);

            Assert.AreEqual(dateString, invertedDateString);
        }
Пример #3
0
        public void GetInvertedDateTime_InvertsDate()
        {
            var dateString   = "0001.01.01_00:00:00";
            var expectedDate = DateTime.MaxValue;

            var actualDate = RowKeyUtils.GetInvertedDateTime(invertedDate: dateString);

            Assert.AreEqual(expectedDate, actualDate);
        }
Пример #4
0
        public void GetExpensesByInvertedDate_Test()
        {
            var rows = new List <string>()
            {
                // [0] poprawny wpis 27.08.2018
                "userCashflow_qwerty_7982.05.07_23:59:59_44f17b78-5967-4496-957f-89a7270c8bcb",
                // [1] poorawny wpis 27.08.2018
                "userCashflow_qwerty_7982.05.07_23:59:59_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [2] poprawny wpis 27.08.2018 tylko rano
                "userCashflow_qwerty_7982.05.07_00:00:00_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [3] niepoprawny wpis - innego użytkownika
                "userCashflow_asdf_7982.05.07_23:59:59_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [4] poprawny wpis 28.08.2018
                "userCashflow_qwerty_7982.05.06_23:59:59_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [5] niepoprawny wpis 28.10.2018
                "userCashflow_qwerty_7982.03.06_23:59:59_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [6] niepoprawny wpis z jakiegoś maja - za wcześnie
                "userCashflow_qwerty_7982.08.06_23:59:59_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [7] poprawny wpis w dzień 26.09.2018
                "userCashflow_qwerty_7982.04.07_00:00:00_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a",
                // [8] poprawny wpis w dzień 26.09.2018
                "userCashflow_qwerty_7982.04.07_23:59:59_d7d572bc-f0ca-4a95-9aca-f5a5c3cf7c0a"
            };

            var prefix   = "userCashflow_qwerty";
            var dateFrom = RowKeyUtils.ConvertInvertedDateToDateFrom(RowKeyUtils.GetInvertedDateString(new DateTime(2018, 08, 27)));
            var dateTo   = RowKeyUtils.ConvertInvertedDateToDateTo(RowKeyUtils.GetInvertedDateString(new DateTime(2018, 09, 26)));

            var dateFromInverted = $"{prefix}_{dateFrom}";
            var dateToInverted   = $"{prefix}_{dateTo}";

            // 27.08.2018
            var expectedDateFromInverted = "userCashflow_qwerty_7982.05.08_00:00:00";
            // 26.09.2018
            var expectedDateToInverted = "userCashflow_qwerty_7982.04.07_00:00:00";

            var list = rows
                       .Where(x => x.CompareTo(dateFromInverted) < 0)
                       .Where(x => x.CompareTo(dateToInverted) > 0)
                       .ToList();

            Assert.AreEqual(expectedDateFromInverted, dateFromInverted);
            Assert.AreEqual(expectedDateToInverted, dateToInverted);
            Assert.Contains(rows[0], list);
            Assert.Contains(rows[1], list);
            Assert.Contains(rows[2], list);
            Assert.False(list.Contains(rows[3]));
            Assert.Contains(rows[4], list);
            Assert.False(list.Contains(rows[5]));
            Assert.False(list.Contains(rows[6]));
            Assert.Contains(rows[7], list);
            Assert.Contains(rows[8], list);
        }
Пример #5
0
        public void GetInvertedDateString_InvertsDate()
        {
            var dateNotInverted    = DateTime.MaxValue;
            var dateInverted       = DateTime.MinValue;
            var dateInvertedString = dateInverted.ToString(RowKeyUtils.DateFormat, CultureInfo.InvariantCulture);

            var actualDateInverted = RowKeyUtils.GetInvertedDateString(dateNotInverted);

            Assert.AreEqual(
                expected: dateInvertedString,
                actual: actualDateInverted);
        }
Пример #6
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(
                 AuthorizationLevel.Function,
                 "get",
                 "post",
                 Route = "messages/getnew/{login}/{dateFrom}")
            ] HttpRequestMessage req,
            string login,
            string dateFrom,
            [Table("ExpensesApp", "message_{login}")] IQueryable <Message> messages,
            TraceWriter log)
        {
            if (login == null)
            {
                log.Info("GetNewMessages response: BadRequest - login is null");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "Please pass a login on the query string or in the request body"));
            }
            if (dateFrom == null)
            {
                log.Info("GetNewMessages response: BadRequest - no datefrom specified");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "No datefrom specified"));
            }

            try
            {
                var dateToCompare = RowKeyUtils.ConvertInvertedDateToDateFrom(RowKeyUtils.InvertDateTimeString(dateFrom));
                log.Info("GetNewMessages, date to compare is " + dateToCompare);
                var list = messages.Where(x => x.RowKey.CompareTo(dateToCompare) < 0).ToList();
                log.Info($"GetNewMessages, found {list.Count} items");
                var listDto = list.Select(x => new GetNewMessagesResponseDto()
                {
                    From    = JsonConvert.DeserializeObject <UserShort>(x.From),
                    Topic   = x.Topic,
                    Content = x.Content,
                    RowKey  = x.RowKey
                }).ToList();
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.OK,
                           value: JsonConvert.SerializeObject(listDto)));
            }
            catch (Exception ex)
            {
                log.Error("GetNewMessages response: InternalServerError - problem with loading messages", ex);
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.InternalServerError,
                           value: "Problem with loading messages"));
            }
        }
Пример #7
0
        public void GetInvertedDateTime_IsInverseFunctionOf_GetInvertedDateString()
        {
            var date = DateTime.Now;

            var invertedDateString = RowKeyUtils.GetInvertedDateString(date);
            var invertedDateTime   = RowKeyUtils.GetInvertedDateTime(invertedDateString);

            Assert.AreEqual(date.Year, invertedDateTime.Year);
            Assert.AreEqual(date.Month, invertedDateTime.Month);
            Assert.AreEqual(date.Day, invertedDateTime.Day);
            Assert.AreEqual(date.Hour, invertedDateTime.Hour);
            Assert.AreEqual(date.Minute, invertedDateTime.Minute);
            Assert.AreEqual(date.Second, invertedDateTime.Second);
        }
Пример #8
0
        private static async Task <TableResult> InsertInvitationMessage(UserDetails invitersDetails, UserLogInData inviter, UserLogInData receiver, CloudTable table, TraceWriter log)
        {
            var date   = DateTime.UtcNow;
            var rowKey = RowKeyUtils.GetInvertedDateString(date);

            string householdOwner = null;

            if (string.IsNullOrEmpty(inviter.HouseholdId))
            {
                householdOwner = inviter.Login;
            }
            else
            {
                var splited = inviter.HouseholdId.Split('_');
                householdOwner = splited.Last();
            }

            var message = new Message()
            {
                PartitionKey = $"message_{receiver.Login}",
                RowKey       = rowKey,
                From         = JsonConvert.SerializeObject(new UserShort()
                {
                    Name  = invitersDetails.Name,
                    Login = inviter.Login
                }),
                Topic   = $"{invitersDetails.Name} invites you to household",
                Content = $"/api/households/accept/{householdOwner}/{receiver.Login}/{rowKey}"
            };

            log.Info("InviteToHousehold: proceeding with inserting invitation message");
            try
            {
                TableOperation insertOperation = TableOperation.Insert(message);
                return(await table.ExecuteAsync(insertOperation));
            }
            catch (Exception ex)
            {
                log.Error("InviteToHousehold: failed to insert invitation message", ex);
                return(null);
            }
        }
Пример #9
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(
                 AuthorizationLevel.Function,
                 "post",
                 Route = "cashflows/add/{login}/")
            ] HttpRequestMessage req,
            string login,
            [Table("ExpensesApp")] ICollector <Cashflow> outTable,
            [Table("ExpensesApp", "user_{login}", "user_{login}")] UserLogInData user,
            [Queue("expenses-addcashflow")] CloudQueue queue,
            [Table("ExpensesApp")] CloudTable table,
            TraceWriter log)
        {
            AddCashFlowDto dto = null;

            try
            {
                log.Info($"json dto: " + req.Content);
                dto = await req.Content.ReadAsDeserializedJson <AddCashFlowDto>();
            }
            catch
            {
                log.Info("AddCashFlow response: BadRequest - cannot read dto object");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "Please pass a valid dto object in the request content"));
            }
            if (login == null)
            {
                log.Info("AddCashFlow response: BadRequest - login is null");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "Please pass a login on the query string or in the request body"));
            }
            if (user == null)
            {
                log.Info($"AddCashFlow response: BadRequest - user does not exist");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "User with given login does not exist"
                           ));
            }

            var cashflowBase = new Cashflow()
            {
                DateTime     = dto.DateTime,
                CategoryGuid = dto.CategoryGuid,
                Amount       = JsonConvert.SerializeObject(dto.Amount),
                Details      = JsonConvert.SerializeObject(dto.Details),
                WalletGuid   = dto.WalletGuid
            };
            var dateTimeInverted = RowKeyUtils.GetInvertedDateString(dto.DateTime);
            var guid             = Guid.NewGuid();

            if (user.BelongsToGroup)
            {
                var cashflowHousehold = new Cashflow(cashflowBase)
                {
                    PartitionKey = user.HouseholdId,
                    RowKey       = $"householdCashflow_{dateTimeInverted}_{guid}"
                };
                outTable.Add(cashflowHousehold);
                log.Info($"Added cashflowHousehold PK={cashflowHousehold.PartitionKey} RK={cashflowHousehold.RowKey}");
            }
            var cashflowUser = new Cashflow(cashflowBase)
            {
                PartitionKey = user.HouseholdId,
                RowKey       = $"userCashflow_{login}_{dateTimeInverted}_{guid}"
            };

            outTable.Add(cashflowUser);
            log.Info($"Added cashflowHousehold PK={cashflowUser.PartitionKey} RK={cashflowUser.RowKey}");

            //var cashflowHouseholdCategory = new Cashflow(cashflowBase)
            //{
            //    PartitionKey = user.HouseholdId,
            //    RowKey = $"householdCategoryCashflow_{dto.CategoryGuid}_{dateTimeInverted}_{guid}"
            //};
            //outTable.Add(cashflowHouseholdCategory);
            //log.Info($"Added cashflowHousehold PK={cashflowHouseholdCategory.PartitionKey} RK={cashflowHouseholdCategory.RowKey}");

            //var cashflowUserCategory = new Cashflow(cashflowBase)
            //{
            //    PartitionKey = user.HouseholdId,
            //    RowKey = $"userCategoryCashflow_{login}_{dto.CategoryGuid}_{dateTimeInverted}_{guid}"
            //};
            //outTable.Add(cashflowUserCategory);
            //log.Info($"Added cashflowHousehold PK={cashflowUserCategory.PartitionKey} RK={cashflowUserCategory.RowKey}");

            var addMessageDto = new AddMessageToAddCashflowQueueDto()
            {
                Amount             = dto.Amount,
                HouseholdPk        = user.HouseholdId,
                HouseholdRk        = user.HouseholdId,
                WalletGuid         = dto.WalletGuid,
                CategoryGuid       = dto.CategoryGuid,
                UserBelongsToGroup = user.BelongsToGroup,
                Login = login
            };

            if (user.BelongsToGroup)
            {
                var message = JsonConvert.SerializeObject(addMessageDto);
                await queue.AddMessageAsync(new CloudQueueMessage(message));

                log.Info($"Enqueued message {message}");
            }
            else
            {
                log.Info("User does not belong to a group. Only his wallet will be updated");
                await UpdateUsersWallet(addMessageDto, table, log);
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }