Skip to content

Commit

Permalink
Implementa api de Eventos
Browse files Browse the repository at this point in the history
  • Loading branch information
rscouto committed Mar 29, 2017
1 parent 15d910f commit 885eb95
Show file tree
Hide file tree
Showing 10 changed files with 515 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@
<Compile Include="ClientConnectionIntegratedTests.cs" />
<Compile Include="CustomerSubscriptionsApiIntegratedTests.cs" />
<Compile Include="DischargeApiIntegratedTests.cs" />
<Compile Include="EventApiIntegratedTest.cs" />
<Compile Include="InstallmentApiIntegratedTests.cs" />
<Compile Include="PagedResponseIntegratedTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
Expand Down
41 changes: 41 additions & 0 deletions BoletoSimplesApiClient.IntegratedTests/EventApiIntegratedTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using NUnit.Framework;
using System.Linq;
using System.Threading.Tasks;

namespace BoletoSimplesApiClient.IntegratedTests
{
[TestFixture]
public class EventApiIntegratedTest : IntegratedTestBase
{
[Test]
public async Task Get_Event_information_with_success()
{
// Arrange
var allEvents = await Client.Events.GetAsync(1, 250).ConfigureAwait(false);
var itemsResponse = await allEvents.GetSuccessResponseAsync().ConfigureAwait(false);

// Act
var response = await Client.Events.GetAsync(itemsResponse.Items.First().Id).ConfigureAwait(false);
var successResponse = await allEvents.GetSuccessResponseAsync().ConfigureAwait(false);
var firstEvent = successResponse.Items.First();

// Assert
Assert.That(response.IsSuccess, Is.True);
Assert.That(firstEvent.Data.Object, Is.Not.Null);
}

[Test]
public async Task List_Events_with_success()
{
// Arrange
var response = await Client.Events.GetAsync(1, 250).ConfigureAwait(false);

// Act
var successResponse = await response.GetSuccessResponseAsync().ConfigureAwait(false);

// Assert
Assert.That(response.IsSuccess, Is.True);
Assert.That(successResponse.Items, Is.Not.Empty);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using BoletoSimplesApiClient.APIs.Installments.Models;
using BoletoSimplesApiClient.UnitTests.Json;
using Newtonsoft.Json;
using NUnit.Framework;
using System;
using System.Net;
Expand Down

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions BoletoSimplesApiClient.UnitTests/Json/JsonConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,17 @@ public static class JsonConstants
'paid_agency': 'Agência de Pagamento'}";

public const string Discharge = @"{'id':132,'filename':'arquivo-test.ret','processed_at':null,'created_via_api':true,'status':'unprocessed','bank_billet_account_id':null,'created_via_integration':null}";

public const string Remittance = @"{ 'filename' : '1605061.REM', 'created_via_api' : true, 'status' : 'processed','bank_billet_account_id' : 1, 'created_at' : '2016-05-06', 'processed_at' : '2016-05-06', 'url' : 'https://sandbox.boletosimples.com.br/remessas/06tt1bcc3f6132720866b53a57c76de4/download', 'id' : 1, 'bank_billet_ids' : [1] }";

public const string Installment = @"{'id':1,'amount':1120.4,'cycle':'monthly','start_at':'2016-09-15','end_at':'2016-11-16','instructions':null,'customer_id':11,'description':'Hospedagem','created_at':'2016-08-15','updated_at':'2016-08-15','created_via_api':true,'total':3,'bank_billet_account_id':12,'status':'created','fine_for_delay': 0.0,'late_payment_interest':0.0}";

public const string CurstomerSubscription = @"{'id':1,'amount':1120.4,'cycle':'monthly','next_billing':'2017-01-01','end_at':'2016-11-16','instructions':null,'customer_id':11,'description':'Hospedagem','bank_billet_account_id':12,'fine_for_delay': 0.0,'late_payment_interest':0.0}";

public const string Event = @"{'id': 224,'code': 'customer.updated','data': { 'object': {'id': 67,'city_name': 'Rio de Janeiro','person_name': 'Joao da Silva','address': 'Rua quinhentos',
'address_complement': 'Sala 4','address_number': '111','mobile_number': '','cnpj_cpf': '782.661.177-64','email': 'novo@example.com','neighborhood': 'bairro',
'person_type': 'individual','phone_number': '2112123434','zipcode': '12312-123','mobile_local_code': '','state': 'RJ','created_via_api': true },
'changes': {'email': [ 'antigo@example.com', 'novo@example.com'],'mobile_local_code': [ null, ''],'mobile_number': [ null, ''],
'updated_at': [ '2015-03-08 19:27:36 -0300', '2015-03-17 21:37:53 -0300'] }},'occurred_at': '2015-03-17T21:37:53.000-03:00' }";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using BoletoSimplesApiClient.APIs.Remittances.Models;
using BoletoSimplesApiClient.APIs.Installments.Models;
using BoletoSimplesApiClient.APIs.CustomerSubscriptions.Models;
using BoletoSimplesApiClient.APIs.Events.Models;

namespace BoletoSimplesApiClient.UnitTests.Json
{
Expand Down Expand Up @@ -132,15 +133,39 @@ public async Task Given_input_json_of_model_CustomerSubscription_should_be_seria
firstCustomerSubscription = await Task.FromResult(JsonConvert.DeserializeObject<CustomerSubscription>(JsonConstants.CurstomerSubscription))
.ConfigureAwait(false);

var customerSunbscriptionJson = await Task.FromResult(JsonConvert.SerializeObject(firstCustomerSubscription))
var customerSubscriptionJson = await Task.FromResult(JsonConvert.SerializeObject(firstCustomerSubscription))
.ConfigureAwait(false);

secondCustomerSubscription = await Task.FromResult(JsonConvert.DeserializeObject<CustomerSubscription>(customerSunbscriptionJson))
secondCustomerSubscription = await Task.FromResult(JsonConvert.DeserializeObject<CustomerSubscription>(customerSubscriptionJson))
.ConfigureAwait(false);
});

// Other Asserts
firstCustomerSubscription.ShouldBeEquivalentTo(secondCustomerSubscription);
}

[Test]
public async Task Given_input_json_of_model_Event_should_be_serialize_and_desesialize_right()
{
// Arrange
EventData firstEventData = null;
EventData secondEventData = null;

// Act && Assert
Assert.DoesNotThrowAsync(async () =>
{
firstEventData = await Task.FromResult(JsonConvert.DeserializeObject<EventData>(JsonConstants.Event))
.ConfigureAwait(false);

var eventDataJson = await Task.FromResult(JsonConvert.SerializeObject(firstEventData))
.ConfigureAwait(false);

secondEventData = await Task.FromResult(JsonConvert.DeserializeObject<EventData>(eventDataJson))
.ConfigureAwait(false);
});

// Other Asserts
firstEventData.ShouldBeEquivalentTo(secondEventData);
}
}
}
66 changes: 66 additions & 0 deletions BoletoSimplesApiClient/APIs/Events/EventsApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using BoletoSimplesApiClient.APIs.Events.Models;
using BoletoSimplesApiClient.Common;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace BoletoSimplesApiClient.APIs.Events
{
/// <summary>
/// Api para consulta de eventos
/// </summary>
public sealed class EventsApi
{
private readonly BoletoSimplesClient _client;
private readonly HttpClientRequestBuilder _requestBuilder;
private const string EVENTS_API = "/events";

public EventsApi(BoletoSimplesClient client)
{
_client = client;
_requestBuilder = new HttpClientRequestBuilder(client);
}

/// <summary>
/// Informações do evento
/// </summary>
/// <param name="id">id do evento</param>
/// <returns>Obtêm informações do evento</returns>
/// <see cref="http://api.boletosimples.com.br/reference/v1/events/#informações-do-evento"/>
public async Task<ApiResponse<EventData>> GetAsync(int id)
{
var request = _requestBuilder.To(_client.Connection.GetBaseUri(), $"{EVENTS_API}/{id}")
.WithMethod(HttpMethod.Get)
.Build();

return await _client.SendAsync<EventData>(request);
}

/// <summary>
/// Listar eventos paginado
/// </summary>
/// <param name="pageNumber">Numero da página</param>
/// <param name="maxPerPage">Quantidade máxima por pagina, máximo e default são 250 items por página</param>
/// <returns>Um resultado paginado contendo uma lista de eventos</returns>
/// <exception cref="ArgumentException">Parametro máx per page superior ao limite de 250 itens</exception>
/// <see cref="http://api.boletosimples.com.br/reference/v1/events/#listar-eventos"/>
public async Task<PagedApiResponse<EventData>> GetAsync(int pageNumber, int maxPerPage = 250)
{
if (maxPerPage > 250)
throw new ArgumentException("o valor máximo para o argumento maxPerPage é 250");


var request = _requestBuilder.To(_client.Connection.GetBaseUri(), EVENTS_API)
.WithMethod(HttpMethod.Get)
.AppendQuery(new Dictionary<string, string>
{
["page"] = pageNumber.ToString(),
["per_page"] = maxPerPage.ToString()
})
.Build();

return await _client.SendPagedAsync<EventData>(request);
}
}
}
38 changes: 38 additions & 0 deletions BoletoSimplesApiClient/APIs/Events/Models/EventData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using BoletoSimplesApiClient.Common;
using System;
using System.Collections.Generic;

namespace BoletoSimplesApiClient.APIs.Events.Models
{
[JsonRoot("event")]
public class EventData
{
/// <summary>
/// ID do carnê
/// </summary>
public int Id { get; set; }

/// <summary>
/// Código do evento
/// </summary>
/// <see cref="http://api.boletosimples.com.br/webhooks/events"/>
public string Code { get; set; }

/// <summary>
/// Mais informações relativas ao evento
/// </summary>
/// <see cref="http://api.boletosimples.com.br/webhooks/payloads"/>
public EventDetail Data { get; set; }

/// <summary>
/// ID do carnê
/// </summary>
public DateTime? OccurredAt { get; set; }
}

public class EventDetail
{
public object Object { get; set; }
public Dictionary<string, string[]> Changes { get; set; }
}
}
4 changes: 2 additions & 2 deletions BoletoSimplesApiClient/BoletoSimplesApiClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@
<Compile Include="APIs\CustomerSubscriptions\Models\CustomerSubscription.cs" />
<Compile Include="APIs\Discharges\DischargesApi.cs" />
<Compile Include="APIs\Discharges\Models\Discharge.cs" />
<Compile Include="APIs\Events\EventsApi.cs" />
<Compile Include="APIs\Events\Models\EventData.cs" />
<Compile Include="APIs\Installments\InstallmentsApi.cs" />
<Compile Include="APIs\Installments\Models\Installment.cs" />
<Compile Include="APIs\Remittances\Models\Remittance.cs" />
Expand All @@ -107,8 +109,6 @@
<ItemGroup>
<Folder Include="APIs\Customers\RequestMessages\" />
<Folder Include="APIs\Customers\ResponseMessages\" />
<Folder Include="APIs\Events\RequestMessages\" />
<Folder Include="APIs\Events\ResponseMessages\" />
<Folder Include="APIs\WebhookDeliveries\RequestMessages\" />
<Folder Include="APIs\WebhookDeliveries\ResponseMessages\" />
<Folder Include="APIs\Webhooks\RequestMessages\" />
Expand Down
7 changes: 7 additions & 0 deletions BoletoSimplesApiClient/BoletoSimplesClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using BoletoSimplesApiClient.APIs.BankBillets;
using BoletoSimplesApiClient.APIs.CustomerSubscriptions;
using BoletoSimplesApiClient.APIs.Discharges;
using BoletoSimplesApiClient.APIs.Events;
using BoletoSimplesApiClient.APIs.Installments;
using BoletoSimplesApiClient.APIs.Remittances;
using BoletoSimplesApiClient.Common;
Expand Down Expand Up @@ -55,6 +56,11 @@ public class BoletoSimplesClient : IDisposable
/// </summary>
public readonly CustomerSubscriptionApi CustomerSubscriptions;

/// <summary>
/// EventsApi Api de eventos
/// </summary>
public readonly EventsApi Events;

private readonly HttpClient _client;

/// <summary>
Expand Down Expand Up @@ -88,6 +94,7 @@ public BoletoSimplesClient(HttpClient client, ClientConnection clientConnection)
Remittances = new RemittancesApi(this);
Installments = new InstallmentsApi(this);
CustomerSubscriptions = new CustomerSubscriptionApi(this);
Events = new EventsApi(this);
}

internal async Task<ApiResponse<T>> SendAsync<T>(HttpRequestMessage request)
Expand Down

0 comments on commit 885eb95

Please sign in to comment.