Exemplo n.º 1
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            var model          = JsonConvert.DeserializeObject <Spot>(request.Body);
            var databaseClient = new DatabaseClient <Spot>(new AmazonDynamoDBClient(), new ConsoleLogger());
            var updated        = databaseClient.Create(model);

            response.Body = JsonConvert.SerializeObject(updated);
        }
Exemplo n.º 2
0
        /// <summary>
        /// This method gets called by the runtime.
        /// Use it to add services to the container.
        /// </summary>
        /// <param name="services">An instance of the collection of runtime services
        /// like MVC, Logging and security.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddScoped <ISessionRepository, SessionRepository>();
            services.AddScoped <IMessageRepository, MessageRepository>();

            services.AddSingleton(provider => DatabaseClient.Create(this.Configuration.GetConnectionString("Connection")));
        }
Exemplo n.º 3
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            var receipt                 = JsonConvert.DeserializeObject <Receipt>(request.Body);
            var dbClient                = new AmazonDynamoDBClient();
            var logger                  = new ConsoleLogger();
            var receiptDbClient         = new DatabaseClient <ReceiptSaveResult>(dbClient, logger);
            var spotReservationDbClient = new DatabaseClient <SpotReservation>(dbClient, logger);
            var vendorDbClient          = new DatabaseClient <Vendor>(dbClient, logger);
            var qboClient               = new QuickBooksOnlineClient(PrivateAccounting.Constants.LakelandMiPuebloRealmId, new DatabaseClient <QuickBooksOnlineConnection>(dbClient, logger), logger);

            var allActiveCustomers = qboClient
                                     .QueryAll <Customer>("select * from customer")
                                     .ToDictionary(x => x.Id);
            var activeVendors = new ActiveVendorSearch()
                                .GetActiveVendors(allActiveCustomers, vendorDbClient)
                                .ToList();
            var spotClient           = new DatabaseClient <Spot>(dbClient, logger);
            var spotReservationCheck = new SpotReservationCheck(spotClient, spotReservationDbClient, activeVendors, allActiveCustomers);
            var validation           = new ReceiptValidation(spotReservationCheck).Validate(receipt).Result;

            if (validation.Any())
            {
                response.StatusCode = 400;
                response.Body       = new JObject {
                    { "error", JArray.FromObject(validation) }
                }.ToString();
                return;
            }
            var    taxRate        = new Tax().GetTaxRate(qboClient, PropertyRentalManagement.Constants.QUICKBOOKS_RENTAL_TAX_RATE);
            var    cardPayment    = new CardPayment(logger, Configuration.CLOVER_MI_PUEBLO_PRIVATE_TOKEN);
            var    receiptService = new ReceiptSave(receiptDbClient, qboClient, taxRate, spotReservationDbClient, logger, cardPayment);
            string customerId     = receipt.Customer.Id;

            if (string.IsNullOrWhiteSpace(customerId))
            {
                var customer = new Customer {
                    DisplayName = receipt.Customer.Name
                };
                customer   = qboClient.Create(customer);
                customerId = customer.Id.ToString();
            }
            var vendor = activeVendors.FirstOrDefault(x => x.QuickBooksOnlineId.GetValueOrDefault().ToString() == customerId)
                         ?? vendorDbClient.Create(VendorService.CreateModel(int.Parse(customerId), null, null, null));

            receipt.Id = string.IsNullOrWhiteSpace(receipt.Id) ? Guid.NewGuid().ToString() : receipt.Id; // Needed until UI is deployed.
            var receiptResult = receiptService.SaveReceipt(receipt, customerId, user.FirstName, user.LastName, user.Email, vendor, IpLookup.GetIp(request));

            response.Body = JsonConvert.SerializeObject(receiptResult);
        }
Exemplo n.º 4
0
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response, FinanceUser user)
        {
            var dbClient             = new AmazonDynamoDBClient();
            var qboDbClient          = new DatabaseClient <QuickBooksOnlineConnection>(dbClient, new ConsoleLogger());
            var qboClient            = new QuickBooksOnlineClient(PrivateAccounting.Constants.LakelandMiPuebloRealmId, qboDbClient, new ConsoleLogger());
            var vendorClient         = new DatabaseClient <PropertyRentalManagement.DatabaseModel.Vendor>(dbClient, new ConsoleLogger());
            var nonRentalCustomerIds = PropertyRentalManagement.Constants.NonRentalCustomerIds;
            var allActiveCustomers   = qboClient.QueryAll <Customer>("select * from customer")
                                       .Where(x => !nonRentalCustomerIds.Contains(x.Id.GetValueOrDefault()))
                                       .ToDictionary(x => x.Id);
            var activeVendors = new ActiveVendorSearch().GetActiveVendors(allActiveCustomers, vendorClient)
                                .ToDictionary(x => x.QuickBooksOnlineId);
            var newCustomers = allActiveCustomers.Where(x => !activeVendors.ContainsKey(x.Key));

            foreach (var newCustomer in newCustomers)
            {
                var vendor = VendorService.CreateModel(newCustomer.Key, null, null, null);
                vendorClient.Create(vendor);
                activeVendors.Add(vendor.QuickBooksOnlineId, vendor);
            }

            var json = new List <CustomerPaymentSettingsModel>();

            foreach (var vendor in activeVendors.Values)
            {
                var customer = allActiveCustomers[vendor.QuickBooksOnlineId];
                json.Add(new CustomerPaymentSettingsModel
                {
                    Id = vendor.Id,
                    QuickBooksOnlineId = vendor.QuickBooksOnlineId,
                    PaymentFrequency   = vendor.PaymentFrequency,
                    RentPrice          = vendor.RentPrice,
                    Memo        = vendor.Memo,
                    FirstName   = customer.GivenName,
                    LastName    = customer.FamilyName,
                    DisplayName = customer.DisplayName,
                    Balance     = customer.Balance,
                    Spots       = vendor.Spots
                });
            }
            response.Body = JsonConvert.SerializeObject(json);
        }
        public void CreateUser(string email, bool agreedToLicense, string ip)
        {
            var user = new FinanceUser
            {
                Id       = Guid.NewGuid().ToString(),
                Email    = email,
                Biweekly = new List <JObject>(),
                MonthlyRecurringExpenses = new List <JObject>(),
                WeeklyRecurringExpenses  = new List <JObject>(),
                LicenseAgreement         = new LicenseAgreement
                {
                    AgreedToLicense = agreedToLicense,
                    Date            = DateTime.UtcNow.ToString("O"),
                    IpAddress       = ip
                }
            };
            var dbClient = new DatabaseClient <FinanceUser>(new AmazonDynamoDBClient(), new ConsoleLogger());

            dbClient.Create(user);
        }
Exemplo n.º 6
0
        public FinanceUserBankAccount GetAndCacheFinanceUserBankAccount(
            FinanceUser user,
            DatabaseClient <FinanceUserBankAccount> userBankAccountClient)
        {
            Console.WriteLine("Getting account data from plaid");
            var failedAccounts         = new List <FinanceUserBankAccountFailedAccount>();
            var accounts               = new ConcurrentBag <AccountBalance>();
            var institutionsDictionary = new ConcurrentDictionary <string, string>();

            user.BankLinks ??= new List <BankLink>();
            var client = Configuration.BankClient;

            Parallel.ForEach(user.BankLinks, new ParallelOptions {
                MaxDegreeOfParallelism = 10
            }, (bankLink) =>
            {
                try
                {
                    var accountBalance = client.GetAccountBalance(bankLink.AccessToken);
                    institutionsDictionary.TryAdd(
                        accountBalance.Item["institution_id"].Value <string>(),
                        accountBalance.Item["institution_id"].Value <string>());
                    accounts.Add(accountBalance);
                }
                catch (Exception e)
                {
                    failedAccounts.Add(new FinanceUserBankAccountFailedAccount
                    {
                        ItemId           = bankLink.ItemId,
                        ErrorDescription = e.ToString(),
                        InstitutionName  = bankLink.InstitutionName
                    });
                }
            });
            var institutionDetails = new ConcurrentBag <JObject>();

            Parallel.ForEach(institutionsDictionary.Keys, new ParallelOptions {
                MaxDegreeOfParallelism = 10
            }, institution =>
            {
                institutionDetails.Add(client.GetInstitution(institution));
            });
            var institutionsJson = new JArray();

            foreach (var institutionDetail in institutionDetails)
            {
                institutionsJson.Add(institutionDetail["institution"]);
            }
            foreach (var account in accounts)
            {
                var institutionId = account.Item["institution_id"].Value <string>();
                account.Item["institution"] = institutionsJson.First(x =>
                                                                     string.Equals(x["institution_id"].Value <string>(), institutionId, StringComparison.OrdinalIgnoreCase));
            }
            var financeUserBankAccount = new FinanceUserBankAccount
            {
                Email          = user.Email,
                AllAccounts    = JArray.FromObject(accounts),
                FailedAccounts = failedAccounts,
                Updated        = DateTime.UtcNow.ToString("O")
            };

            userBankAccountClient.Create(financeUserBankAccount);
            return(financeUserBankAccount);
        }
Exemplo n.º 7
0
        public async Task Index(IIndex indexer, ClassificationModel messageModel)
        {
            var dbClient = new DatabaseClient <ClassificationModel>(DbClient);
            var existing = dbClient.Get(new ClassificationModel {
                Source = messageModel.Source, PageId = messageModel.PageId
            });
            var activelyCrawledSources = new List <string>();

            if (existing != null && !activelyCrawledSources.Any(x => string.Equals(existing.Source, x, StringComparison.OrdinalIgnoreCase)))
            {
                throw new ProtectedClassificationException(
                          $"This record has already been crawled and is now protected: {messageModel.Source} - {messageModel.PageId}." +
                          " If you want to re-crawl the record delete it in dynamodb, but all associated data will be overwritten when re-crawled.");
            }
            var indexResult = await indexer.Index(messageModel.PageId, existing);

            if (indexResult == null ||
                indexResult.Model == null ||
                indexResult.ImageJpeg == null)
            {
                var missingContent = new List <string>();
                if (indexResult?.Model == null)
                {
                    missingContent.Add("metadata");
                }
                if (indexResult?.ImageJpeg == null)
                {
                    missingContent.Add("binary");
                }
                throw new NoIndexContentException($"The following items are missing for the image {messageModel.Source} - {messageModel.PageId}: {string.Join(", ", missingContent)}");
            }
            else
            {
                var classification = indexResult.Model;
                if (indexResult.ImageJpeg != null)
                {
                    await using var imageStream = new MemoryStream();
                    await indexResult.ImageJpeg.SaveAsJpegAsync(imageStream);

                    await S3Client.PutObjectAsync(
                        new PutObjectRequest
                    {
                        BucketName  = Constants.IMAGES_BUCKET + "/" + indexer.ImagePath,
                        Key         = $"page-id-{indexResult.Model.PageId}.jpg",
                        InputStream = imageStream
                    });

                    classification.Height      = indexResult.ImageJpeg.Height;
                    classification.Width       = indexResult.ImageJpeg.Width;
                    classification.Orientation = indexResult.ImageJpeg.Height >= indexResult.ImageJpeg.Width
                        ? Constants.ORIENTATION_PORTRAIT
                        : Constants.ORIENTATION_LANDSCAPE;
                    var thumbnailBytes = ImageCompression.CreateThumbnail(imageStream.ToArray(), 200, 200, KnownResamplers.Lanczos3);
                    await using var thumbnailStream = new MemoryStream(thumbnailBytes);
                    await S3Client.PutObjectAsync(new PutObjectRequest
                    {
                        BucketName  = $"{Constants.IMAGES_BUCKET}/{indexer.ImagePath}/thumbnails",
                        Key         = $"page-id-{indexResult.Model.PageId}.jpg",
                        InputStream = thumbnailStream
                    });

                    indexResult.ImageJpeg.Dispose();
                }
                else
                {
                    classification.Height      = existing.Height;
                    classification.Width       = existing.Width;
                    classification.Orientation = existing.Orientation;
                }
                classification.Name            = HttpUtility.HtmlDecode(classification.Name);
                classification.Date            = HttpUtility.HtmlDecode(classification.Date);
                classification.OriginalArtist  = HttpUtility.HtmlDecode(classification.OriginalArtist);
                classification.Artist          = Classifier.NormalizeArtist(HttpUtility.HtmlDecode(classification.OriginalArtist));
                classification.TimeStamp       = DateTime.UtcNow.ToString("O");
                classification.Nudity          = false;
                classification.S3Path          = indexer.ImagePath + "/" + $"page-id-{indexResult.Model.PageId}.jpg";
                classification.S3ThumbnailPath = indexer.ImagePath + "/thumbnails/" + $"page-id-{indexResult.Model.PageId}.jpg";
                classification.S3Bucket        = Constants.IMAGES_BUCKET;
                var json = JObject.FromObject(classification,
                                              new JsonSerializer {
                    NullValueHandling = NullValueHandling.Ignore
                });
                await ElasticSearchClient.SendToElasticSearch(classification);

                var artistClient    = new DatabaseClient <ArtistModel>(DbClient);
                var newArtistRecord = new ArtistModel {
                    Artist = classification.Artist, OriginalArtist = classification.OriginalArtist
                };
                var artistRecord = artistClient.Get(newArtistRecord);
                if (artistRecord == null)
                {
                    artistClient.Create(newArtistRecord);
                }
                await DbClient.PutItemAsync(
                    new ClassificationModel().GetTable(),
                    Document.FromJson(json.ToString()).ToAttributeMap()
                    );

                Console.WriteLine($"Indexed: { messageModel.Source} { messageModel.PageId}");
            }
        }