Advertisement
CharlesLindsay

Untitled

Mar 12th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.23 KB | None | 0 0
  1. using Amazon.CognitoIdentityProvider;
  2. using Amazon.CognitoIdentityProvider.Model;
  3. using Enumis.Apply.Api.ServiceInterface.Extensions;
  4. using Enumis.Apply.Api.ServiceModel;
  5. using Enumis.Constants;
  6. using Enumis.Constants.Extensions;
  7. using Enumis.DataModel.DataTypes;
  8. using Enumis.DataModel.Extensions;
  9. using Enumis.DataModel.Indices.GSI.Customer;
  10. using Enumis.DataModel.Tables;
  11. using Enumis.DataModel.Validators;
  12. using Enumis.Interfaces.Applications;
  13. using Enumis.Interfaces.ChangeTracking;
  14. using Enumis.Interfaces.Cognito;
  15. using Enumis.Interfaces.Enums;
  16. using Enumis.Interfaces.Extensions;
  17. using Enumis.Interfaces.Processors.Gps;
  18. using Enumis.Interfaces.Programs;
  19. using Enumis.Utilities.Api.Types;
  20. using Enumis.Utilities.Extensions;
  21. using id3global;
  22. using Serilog;
  23. using ServiceStack;
  24. using ServiceStack.Aws.DynamoDb;
  25. using ServiceStack.Configuration;
  26. using ServiceStack.Text;
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Globalization;
  30. using System.IO;
  31. using System.Linq;
  32. using System.Net;
  33. using Address = Enumis.Interfaces.Applications.Address;
  34.  
  35. namespace Enumis.Apply.Api.ServiceInterface
  36. {
  37. /// <summary>
  38. /// Defines the <see cref="ApplicationService" />
  39. /// </summary>
  40. public class ApplicationService : Service
  41. {
  42. #region Properties
  43.  
  44. /// <summary>
  45. /// Gets or sets the AppSettings
  46. /// </summary>
  47. public IAppSettings AppSettings { get; set; }
  48.  
  49. /// <summary>
  50. /// Gets or sets the CognitoClient
  51. /// </summary>
  52. public AmazonCognitoIdentityProviderClient CognitoClient { get; set; }
  53.  
  54. /// <summary>
  55. /// Gets or sets the CognitoIdentity
  56. /// </summary>
  57. public ICognitoIdentity CognitoIdentity { get; set; }
  58.  
  59. /// <summary>
  60. /// Gets or sets the DynamoDb
  61. /// </summary>
  62. public IPocoDynamo DynamoDb { get; set; }
  63.  
  64. /// <summary>
  65. /// Gets or sets the Log
  66. /// </summary>
  67. public ILogger Log { get; set; }
  68.  
  69. /// <summary>
  70. /// Gets or sets the S3Vault
  71. /// </summary>
  72. public S3Vault S3Vault { get; set; }
  73.  
  74. #endregion
  75.  
  76. #region Methods
  77.  
  78. /// <summary>
  79. /// The Get
  80. /// </summary>
  81. /// <param name="request">The <see cref="ApplicationCardDetailRequest" /></param>
  82. /// <returns>The <see cref="ApplicationCardDetailResponse" /></returns>
  83. public ApplicationCardDetailResponse Get(ApplicationCardDetailRequest request)
  84. {
  85. var application = DynamoDb.GetApplicationByERN(request.ERN).AsIGpsApplication();
  86.  
  87. return application?.CardProcessor?.Response == null
  88. ? new ApplicationCardDetailResponse()
  89. : application.CardProcessor.Response.ConvertTo<ApplicationCardDetailResponse>();
  90. }
  91.  
  92. /// <summary>
  93. /// The Get
  94. /// </summary>
  95. /// <param name="request">The <see cref="ApplicationsRequest" /></param>
  96. /// <returns>The <see cref="ApplicationsResponse" /></returns>
  97. public ApplicationsResponse Get(ApplicationsRequest request)
  98. {
  99. var applications = GetGpsApplications().AsApplicationsWeb();
  100. var applicationsResponse = new ApplicationsResponse
  101. {
  102. Applications = applications.Where(x => x.State == ApplicationState.Success).ToList(),
  103. Application = applications.FirstOrDefault(x => x.State < ApplicationState.Success)
  104. };
  105.  
  106. return applicationsResponse;
  107. }
  108.  
  109. /// <summary>
  110. /// The Post
  111. /// </summary>
  112. /// <param name="request">The <see cref="ApplicationKycRequest" /></param>
  113. /// <returns>The <see cref="ApplicationKycResponse" /></returns>
  114. public ApplicationKycResponse Post(ApplicationKycRequest request)
  115. {
  116. var authenticateClient =
  117. new GlobalAuthenticateClient(GlobalAuthenticateClient.EndpointConfiguration
  118. .wsHttpBinding_GlobalAuthenticate);
  119.  
  120. authenticateClient.ClientCredentials.UserName.UserName = "ryan.helms@enumis.co.uk";
  121. authenticateClient.ClientCredentials.UserName.Password = "40%4MKy4yZdaCKclx1RC";
  122.  
  123. var input = new GlobalInputData
  124. {
  125. Personal = new GlobalPersonal
  126. {
  127. PersonalDetails = request.GetPersonalDetails()
  128. },
  129. Addresses = new GlobalAddresses
  130. {
  131. CurrentAddress = request.GetCurrentAddress(),
  132. HistoricAddresses = request.GetHistoricAddresses()
  133. }
  134. };
  135.  
  136. var profile = new GlobalProfileIDVersion
  137. {
  138. ID = new Guid("7c2bcf5a-2fae-456b-995c-450630fb2621"),
  139. Version = 0
  140. };
  141.  
  142. // Log("||ApplicationKycRequest||", "Profile:", profile.ToJson());
  143. // Log("||ApplicationKycRequest||", "Input:", input.ToJson());
  144.  
  145. var result = authenticateClient.AuthenticateSPAsync(profile, "", input).ConfigureAwait(false).GetAwaiter().GetResult();
  146.  
  147. // Log("||ApplicationKycRequest||", "Result:", result.ToJson());
  148.  
  149. var response = new ApplicationKycResponse
  150. {
  151. Decision = result.BandText,
  152. Score = result.Score.ToString(),
  153. AuthenticationId = result.AuthenticationID.ToString(),
  154. Timestamp = result.Timestamp.ToString(CultureInfo.InvariantCulture)
  155. };
  156.  
  157. // Log("||ApplicationKycRequest||", "Response:", response.ToJson());
  158.  
  159. return response;
  160. }
  161.  
  162. /// <summary>
  163. /// The Get
  164. /// </summary>
  165. /// <param name="request">The <see cref="ApplyRegistrationRequest" /></param>
  166. /// <returns>The <see cref="ApplyRegistrationResponse" /></returns>
  167. public ApplyRegistrationResponse Post(ApplyRegistrationRequest request)
  168. {
  169. try
  170. {
  171. var addUserToGroupResult = AddUserToGroup(CognitoIdentity.Username);
  172.  
  173. Log.Debug("||ApplicationKycRequest|| Add User To Group Result: {@AddUserToGroupResults}", addUserToGroupResult);
  174.  
  175. return new ApplyRegistrationResponse
  176. {
  177. AddUserToGroupResponse = addUserToGroupResult
  178. };
  179. }
  180. catch (Exception ex)
  181. {
  182. throw new HttpError(HttpStatusCode.BadRequest, ex.Message);
  183. }
  184. }
  185.  
  186. /// <summary>
  187. /// The Post
  188. /// </summary>
  189. /// <param name="request">The <see cref="AssetUploadRequest" /></param>
  190. /// <returns>The <see cref="AssetUploadResponse" /></returns>
  191. public AssetUploadResponse Post(AssetUploadRequest request)
  192. {
  193. try
  194. {
  195. request.ERN.ThrowIfNullOrEmpty("Application ERN cannot be empty");
  196. request.Link.ThrowIfNullOrEmpty("Asset file name cannot be empty");
  197. request.Bytes.ThrowIfNull("Asset Bytes cannot be empty");
  198.  
  199. Log.Debug("File Received: {@AssetUploadRequest}", request);
  200.  
  201. var originalApplication = DynamoDb.GetApplicationByERN(request.ERN).AsIGpsApplication();
  202. originalApplication.ThrowIfNull();
  203.  
  204. var destinationName = $"{request.Type.ToString().ToLower()}{Path.GetExtension(request.Link)}";
  205. var destination = $"applications/{originalApplication.CustomerERN}/{originalApplication.ERN}/{destinationName}";
  206.  
  207. S3Vault.WriteFile(destination, new MemoryStream(request.Bytes));
  208.  
  209.  
  210. Log.Information("Image Saved: {AssetUploadDestination}", destination);
  211.  
  212. request.Bytes = null;
  213. request.Link = destinationName;
  214.  
  215. // Lets upate or add
  216. var applicationAsset = request.ConvertTo<ApplicationAsset>();
  217. var existingAsset = originalApplication.Form.Assets.FirstOrDefault(x => x.Type == request.Type && x.Domain == request.Domain);
  218.  
  219. if (existingAsset != null)
  220. {
  221. applicationAsset.GetChanges(existingAsset).AsModifications().SaveTo(originalApplication);
  222. originalApplication.Form.Assets.Remove(existingAsset);
  223. }
  224.  
  225. originalApplication.Form.Assets.Add(applicationAsset);
  226.  
  227. // Lets move the state of the application
  228. switch (originalApplication.State)
  229. {
  230. case ApplicationState.UploadIdentificationDocuments:
  231. if (originalApplication.Form.Assets.Any(x => x.Domain == ApplicationAssetDomain.Identification && (int)x.Type < 1000))
  232. originalApplication.State++;
  233. break;
  234. case ApplicationState.UploadAddressDocuments:
  235. var cutoff = 999;
  236. if (originalApplication.Form.Assets.Any(x => x.Domain == ApplicationAssetDomain.Identification && x.Type == ApplicationAssetType.DriversLicense)) cutoff = 1000;
  237. if (originalApplication.Form.Assets.Count(x => x.Domain == ApplicationAssetDomain.Address && (int)x.Type >= cutoff) > 1)
  238. originalApplication.State++;
  239. break;
  240. }
  241.  
  242. originalApplication.BumpModifyDate();
  243. DynamoDb.PutItem(originalApplication.ToDynamoDb());
  244.  
  245. return originalApplication.ConvertTo<AssetUploadResponse>();
  246. }
  247. catch (Exception ex)
  248. {
  249. Log.Fatal(ex, ex.ToString());
  250. throw new HttpError(HttpStatusCode.BadRequest, ex.Message);
  251. }
  252. }
  253.  
  254. /// <summary>
  255. /// The Post
  256. /// </summary>
  257. /// <param name="request">The <see cref="ProcessApplicationRequest" /></param>
  258. /// <returns>The <see cref="ProcessApplicationResponse" /></returns>
  259. public ProcessApplicationResponse Post(ProcessApplicationRequest request)
  260. {
  261. try
  262. {
  263. var application = GetApplication(CognitoIdentity.Sub, CognitoIdentity.Email);
  264. Log.Debug("Returning Application {@application}", application);
  265. return application.ConvertTo<ProcessApplicationResponse>();
  266. }
  267. catch (Exception ex)
  268. {
  269. throw new HttpError(HttpStatusCode.BadRequest, ex.Message);
  270. }
  271. }
  272.  
  273. /// <summary>
  274. /// The Put
  275. /// </summary>
  276. /// <param name="request">The <see cref="ProcessApplicationRequest" /></param>
  277. /// <returns>The <see cref="ProcessApplicationResponse" /></returns>
  278. public ProcessApplicationResponse Put(ProcessApplicationRequest request)
  279. {
  280. try
  281. {
  282. request.ThrowIfNull("Incomming request should not be null");
  283. Log.Debug("Incomming Request {@ProcessApplicationRequest}", request);
  284.  
  285. var application = GetCurrentApplication(request.ConvertTo<GpsApplication>());
  286. application.ThrowIfNull("Application should not be null");
  287. Log.Debug("Current Application: {@CurrentApplication}", application);
  288.  
  289.  
  290. var processedApplication = ProcessApplication(application);
  291.  
  292. return processedApplication.ConvertTo<ProcessApplicationResponse>();
  293. }
  294. catch (Exception ex)
  295. {
  296. throw new HttpError(HttpStatusCode.BadRequest, ex.Message);
  297. }
  298. }
  299.  
  300. /// <summary>
  301. /// The AddUserToGroup
  302. /// </summary>
  303. /// <param name="username">The <see cref="string" /></param>
  304. /// <returns>The <see cref="AdminAddUserToGroupResponse" /></returns>
  305. private AdminAddUserToGroupResponse AddUserToGroup(string username)
  306. {
  307. return CognitoClient.AdminAddUserToGroupAsync(new AdminAddUserToGroupRequest
  308. {
  309. UserPoolId = AppSettings.GetString("COGNITO_USERPOOL_ID"),
  310. Username = username,
  311. GroupName = "system:apply"
  312. }).GetAwaiter().GetResult();
  313. }
  314.  
  315. /// <summary>
  316. /// The CompleteNewRegistration
  317. /// </summary>
  318. /// <param name="application">The <see cref="IApplicationComplete" /></param>
  319. private void CompleteNewRegistration(IApplicationComplete application)
  320. {
  321. if (!application.IsNewRegistration) return;
  322.  
  323. var registration = DynamoDb.GetRegistrationByCognitoUserId(CognitoIdentity.Sub);
  324. var originalRegistration = registration.Clone();
  325.  
  326. // TODO: Need to fill these in with valid data
  327. //AccountCode = "AccountCode".ToNewERN()
  328. if (!registration.BirthDate.HasValue) registration.BirthDate = DateTime.Parse($"{application.Form.DobYear}-{application.Form.DobMonth}-{application.Form.DobDay}").ToUnixTimeMs();
  329. if (string.IsNullOrWhiteSpace(registration.Title)) registration.Title = application.Form.Title;
  330. if (string.IsNullOrWhiteSpace(registration.FirstName)) registration.FirstName = application.Form.FirstName;
  331. if (string.IsNullOrWhiteSpace(registration.MiddleName)) registration.MiddleName = application.Form.MiddleName;
  332. if (string.IsNullOrWhiteSpace(registration.LastName)) registration.LastName = application.Form.LastName;
  333. if (!registration.OriginCountry.HasValue) registration.OriginCountry = Iso.Countries.FindBy(application.Form.Nationality, false)?.IsoCode?.ToInt() ?? 0;
  334.  
  335. if (registration.GetChanges(originalRegistration).Any())
  336. {
  337. registration.BumpModifyDate();
  338. DynamoDb.PutItem(registration);
  339. }
  340. }
  341.  
  342. /// <summary>
  343. /// The CreateApplication
  344. /// </summary>
  345. /// <param name="registration">The <see cref="Registration" /></param>
  346. /// <returns>The <see cref="IGpsApplication" /></returns>
  347. private IGpsApplication CreateApplication(Registration registration)
  348. {
  349. Log.Debug("Creating new Application for {@Registration}", registration);
  350. var application = new GpsApplication
  351. {
  352. ERN = "Application".ToNewERN(),
  353. CustomerERN = registration.ERN,
  354. CreatedDate = DateTime.UtcNow.ToUnixTimeMs(),
  355. IsNewRegistration = registration.AccountCode.Contains("Accountcode"),
  356. Form = new Form
  357. {
  358. Addresses = new List<Address>
  359. {
  360. new Address()
  361. }
  362. },
  363. Program = new Program
  364. {
  365. Code = "FLOW",
  366. Name = "Flow Card"
  367. }
  368. };
  369.  
  370. var dynamoDb = application.ToDynamoDb();
  371. DynamoDb.PutItem(dynamoDb);
  372.  
  373. Log.Information("Created New Application: {@Application}", application);
  374. return application;
  375. }
  376.  
  377. /// <summary>
  378. /// The generateMockCardOffers
  379. /// </summary>
  380. /// <returns>The <see cref="List{Offer}"/></returns>
  381. private List<Offer> generateMockCardOffers()
  382. {
  383. var mockOffers = new List<Offer>();
  384.  
  385. mockOffers.Add(
  386. new Offer
  387. {
  388. OfferingCode = "XXXXXXXXXXXXX1",
  389. Costs = new Costs
  390. {
  391. ATM = new Rate
  392. {
  393. Abroad = new Fee
  394. {
  395. Value = 200,
  396. Type = FeeType.Fixed
  397. },
  398. Local = new Fee
  399. {
  400. Value = 50,
  401. Type = FeeType.Fixed
  402. },
  403. FxFee = new Fee
  404. {
  405. Value = 0,
  406. Type = FeeType.Fixed
  407. }
  408. },
  409. Spend = new Rate
  410. {
  411. Abroad = new Fee
  412. {
  413. Value = 0,
  414. Type = FeeType.Fixed
  415. },
  416. Local = new Fee
  417. {
  418. Value = 0,
  419. Type = FeeType.Fixed
  420. },
  421. FxFee = new Fee
  422. {
  423. Value = 0,
  424. Type = FeeType.Fixed
  425. }
  426. }
  427. },
  428. Fees = new Fees
  429. {
  430. BankTransfer = new Fee
  431. {
  432. Value = 0,
  433. Type = FeeType.Fixed
  434. },
  435. CreditCard = new Fee
  436. {
  437. Value = 0,
  438. Type = FeeType.Fixed
  439. },
  440. DebitCard = new Fee
  441. {
  442. Value = 0,
  443. Type = FeeType.Fixed
  444. },
  445. Dormancy = new Fee
  446. {
  447. Value = 0,
  448. Type = FeeType.Fixed
  449. },
  450. Monthly = new Fee
  451. {
  452. Value = 0,
  453. Type = FeeType.Fixed
  454. }
  455. },
  456. Limits = new Limits
  457. {
  458. MaxBalance = new Fee
  459. {
  460. Value = 0,
  461. Type = FeeType.Fixed
  462. },
  463. MaxLoadPerDay = new Fee
  464. {
  465. Value = 0,
  466. Type = FeeType.Fixed
  467. },
  468. MaxSpendPerDay = new Fee
  469. {
  470. Value = 0,
  471. Type = FeeType.Fixed
  472. }
  473. }
  474. });
  475.  
  476. mockOffers.Add(new Offer
  477. {
  478. OfferingCode = "XXXXXXXXXXXXX2",
  479. Costs = new Costs
  480. {
  481. ATM = new Rate
  482. {
  483. Abroad = new Fee
  484. {
  485. Value = 0,
  486. Type = FeeType.Fixed
  487. },
  488. Local = new Fee
  489. {
  490. Value = 0,
  491. Type = FeeType.Fixed
  492. },
  493. FxFee = new Fee
  494. {
  495. Value = 0,
  496. Type = FeeType.Fixed
  497. }
  498. },
  499. Spend = new Rate
  500. {
  501. Abroad = new Fee
  502. {
  503. Value = 0,
  504. Type = FeeType.Fixed
  505. },
  506. Local = new Fee
  507. {
  508. Value = 0,
  509. Type = FeeType.Fixed
  510. },
  511. FxFee = new Fee
  512. {
  513. Value = 0,
  514. Type = FeeType.Fixed
  515. }
  516. }
  517. },
  518. Fees = new Fees
  519. {
  520. BankTransfer = new Fee
  521. {
  522. Value = 0,
  523. Type = FeeType.Fixed
  524. },
  525. CreditCard = new Fee
  526. {
  527. Value = 0,
  528. Type = FeeType.Fixed
  529. },
  530. DebitCard = new Fee
  531. {
  532. Value = 0,
  533. Type = FeeType.Fixed
  534. },
  535. Dormancy = new Fee
  536. {
  537. Value = 0,
  538. Type = FeeType.Fixed
  539. },
  540. Monthly = new Fee
  541. {
  542. Value = 0,
  543. Type = FeeType.Fixed
  544. }
  545. },
  546. Limits = new Limits
  547. {
  548. MaxBalance = new Fee
  549. {
  550. Value = 0,
  551. Type = FeeType.Fixed
  552. },
  553. MaxLoadPerDay = new Fee
  554. {
  555. Value = 0,
  556. Type = FeeType.Fixed
  557. },
  558. MaxSpendPerDay = new Fee
  559. {
  560. Value = 0,
  561. Type = FeeType.Fixed
  562. }
  563. }
  564. });
  565.  
  566. return mockOffers;
  567. }
  568.  
  569. /// <summary>
  570. /// The GetApplication
  571. /// </summary>
  572. /// <param name="cognitoId">The <see cref="string" /></param>
  573. /// <param name="cognitoEmail">The <see cref="string" /></param>
  574. /// <returns>The <see cref="IGpsApplication" /></returns>
  575. private IGpsApplication GetApplication(string cognitoId, string cognitoEmail)
  576. {
  577. var registration = DynamoDb.GetRegistrationByCognitoUserId(cognitoId);
  578.  
  579. if (registration == null)
  580. {
  581. registration = new Registration
  582. {
  583. ERN = "Customer".ToNewERN(),
  584. Code = GetCustomerCode(),
  585. CognitoUserId = cognitoId,
  586. EmailAddress = cognitoEmail,
  587. CreatedDate = DateTime.UtcNow.ToUnixTimeMs(),
  588. SecurityQuestions = new List<SecurityQuestion>(),
  589. RegisteredDate = -1,
  590.  
  591. // TODO: Need to fill these in with valid data
  592. AccountCode = "AccountCode".ToNewERN()
  593. //BirthDate = DateTime.Parse(context.RawApplication.DOB).ToUnixTimeMs(),
  594. //Title = context.RawApplication.Title,
  595. //FirstName = context.RawApplication.FirstName,
  596. //LastName = context.RawApplication.LastName,
  597. //AccessCode = context.CreateCardRequest.AccCode,
  598. //OriginCountry = Countries.FindBy(context.RawApplication.Nationality, false)?.IsoCode?.ToInt() ?? 0
  599. };
  600.  
  601. DynamoDb.PutItem(registration);
  602. Log.Information("Created New Registration: {@NewRegistration}", registration);
  603. }
  604.  
  605. var applications = GetGpsApplications();
  606.  
  607. if (!applications.Any(x => x.State < ApplicationState.Success))
  608. return CreateApplication(registration);
  609.  
  610. var application = applications.FirstOrDefault(x => x.State < ApplicationState.Success);
  611. application.ThrowIfNull();
  612.  
  613. Log.Debug("Found Application: {@Application}", application);
  614. return application;
  615. }
  616.  
  617. /// <summary>
  618. /// The GetCurrentApplication
  619. /// </summary>
  620. /// <param name="application">The <see cref="IGpsApplication" /></param>
  621. /// <returns>The <see cref="IGpsApplication" /></returns>
  622. private IGpsApplication GetCurrentApplication(IGpsApplication application)
  623. {
  624. try
  625. {
  626. DynamoDb.ThrowIfNull("DynamoDb should not be null");
  627.  
  628. var registration = DynamoDb.GetRegistrationByCognitoUserId(CognitoIdentity.Sub);
  629. registration.ThrowIfNull($"No registration found => {CognitoIdentity.Sub}");
  630. Log.Debug("Found Registration: {@Registration}", registration);
  631.  
  632. var originalApplication = DynamoDb.GetItem<Application>(new DynamoId(registration.ERN, application.ERN)).AsIGpsApplication();
  633. originalApplication.ThrowIfNull();
  634. Log.Debug("Found Application: {@Application}", originalApplication);
  635.  
  636. // lets normailzie / humanize the data
  637. application.Form.ToTitleCase2All();
  638. application.Form.Addresses.ForEach(x => x.ToTitleCase2All());
  639.  
  640. application.Form.GetChanges(originalApplication.Form).AsModifications().SaveTo(originalApplication);
  641. // Lets merge in just the form
  642. originalApplication.Form.MergeWith(application.Form);
  643.  
  644. return originalApplication;
  645. }
  646. catch (Exception ex)
  647. {
  648. Log.Fatal(ex, nameof(GetCurrentApplication));
  649. throw new HttpError(HttpStatusCode.BadRequest, ex.Message);
  650. }
  651. }
  652.  
  653. /// <summary>
  654. /// The GetCustomerCode
  655. /// </summary>
  656. /// <returns>The <see cref="string" /></returns>
  657. private string GetCustomerCode()
  658. {
  659. string customerCode;
  660. bool exists;
  661.  
  662. do
  663. {
  664. Log.Verbose("Generating Customer Code");
  665.  
  666. customerCode = RandomExtensions.AlphaNumeric(10);
  667.  
  668. var code = customerCode;
  669.  
  670. exists = DynamoDb.Query(DynamoDb.FromQueryIndex<CodeGlobalIndex>(x => x.Code == code)).Any();
  671. } while (exists);
  672.  
  673. Log.Information("Generated Customer Code: {CustomerCode}", customerCode);
  674.  
  675. return customerCode;
  676. }
  677.  
  678. /// <summary>
  679. /// The GetGpsApplications
  680. /// </summary>
  681. /// <returns>The <see cref="List{IGpsApplication}" /></returns>
  682. private List<IGpsApplication> GetGpsApplications()
  683. {
  684. DynamoDb.ThrowIfNull("DynamoDb should not be null");
  685. var registration = DynamoDb.GetRegistrationByCognitoUserId(CognitoIdentity.Sub);
  686. if (registration == null) return new List<IGpsApplication>();
  687.  
  688. Log.Verbose("Looking for Existing Applications: {CustomerERN}", registration.ERN);
  689. var applications = DynamoDb.FromQuery<Application>(x => x.CustomerERN == registration.ERN)
  690. .Exec()
  691. .Select(x => x.AsIGpsApplication())
  692. .ToList();
  693.  
  694. return applications;
  695. }
  696.  
  697. /// <summary>
  698. /// The ProcessApplication
  699. /// </summary>
  700. /// <param name="application">The <see cref="IGpsApplication" /></param>
  701. /// <returns>The <see cref="IGpsApplication" /></returns>
  702. private IGpsApplication ProcessApplication(IGpsApplication application)
  703. {
  704. switch (application.State)
  705. {
  706. case ApplicationState.NewApplication:
  707. ValidateApplicationForm(application);
  708.  
  709. CompleteNewRegistration(application);
  710.  
  711. // TODO: This is a temp try/catch to ensure we continue while KYC is in progress.
  712. try
  713. {
  714. var results = Post(application.Form.ConvertTo<ApplicationKycRequest>());
  715. }
  716. catch (Exception e)
  717. {
  718. Log.Error(e, e.Message);
  719. }
  720. //TODO: how de we interpert / process these results
  721.  
  722. application.State++;
  723. break;
  724. case ApplicationState.UploadIdentificationDocuments:
  725. application.State++;
  726. break;
  727. case ApplicationState.UploadAddressDocuments:
  728. application.State++;
  729.  
  730. // Lets mock some card offer data
  731. application.CardOffers = generateMockCardOffers();
  732. break;
  733. case ApplicationState.AcceptProductOffering:
  734. application.State++;
  735. break;
  736. case ApplicationState.Processing:
  737. application.State++;
  738. break;
  739. case ApplicationState.Pending:
  740. application.State++;
  741. break;
  742. case ApplicationState.Success:
  743. application.State = ApplicationState.NewApplication;
  744. break;
  745. case ApplicationState.Failure:
  746. application.State++;
  747. break;
  748. default:
  749. throw new HttpError(HttpStatusCode.BadRequest, "Applciation State is invlaid");
  750. }
  751.  
  752. application.BumpModifyDate();
  753. DynamoDb.PutItem(application.ToDynamoDb());
  754.  
  755. return application;
  756. }
  757.  
  758. /// <summary>
  759. /// The ValidateApplicationForm
  760. /// </summary>
  761. /// <param name="application">The <see cref="IHasForm" /></param>
  762. private void ValidateApplicationForm(IHasForm application)
  763. {
  764. var newApplicationFormValidator = new NewApplicationFormValidator();
  765. var validationResults = newApplicationFormValidator.Validate(application.Form);
  766. if (!validationResults.IsValid) throw new HttpError(HttpStatusCode.BadRequest, string.Join(Environment.NewLine, validationResults.Errors.Select(x => x.ErrorMessage)));
  767. }
  768.  
  769. #endregion
  770. }
  771. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement