-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCarGreenCardController.cs
405 lines (320 loc) · 16.1 KB
/
CarGreenCardController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
using AssurBox.SDK;
using AssurBox.SDK.Clients;
using AssurBox.SDK.DTO.GreenCard.Car;
using AssurBox.SDK.WebHooks;
using Hangfire;
using iTextSharp.text.pdf;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Caching;
using System.Web.Http;
namespace AssurBox.Samples.API.Insurance.Controllers
{
/// <summary>
/// This controller shows a wah to define a webhook handler for AssurBox
/// </summary>
public class CarGreenCardController : ApiController
{
//http://docs.hangfire.io/en/latest/background-methods/writing-unit-tests.html
private readonly IBackgroundJobClient _jobClient;
public CarGreenCardController() : this(new BackgroundJobClient())
{
}
public CarGreenCardController(IBackgroundJobClient jobClient)
{
_jobClient = jobClient;
}
/// <summary>
/// AssurBox is going to post notification on this endpoint (if configured)
/// AssurBox expects an HTTP 200 response
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// /!\ you need to configure the webhook url in Assurbox
/// <see href=""/> url screenshots !
///
/// ici on va récupérer la demande qui vient d'AssurBox, la sauver et confirmer qu'on l'a bien reçue.
/// Si la réception du message n'est pas confirmée, AssurBox va tenter de ré-envoyer le message pendant un temps
/// et si après un certain nombre de tentatives, la réception n'est toujours pas confirmée, il enverra un email "fallback" avec la demande.
/// </remarks>
[Route("webhook/GreenCard")]
[HttpPost]
public HttpResponseMessage Post(SDK.WebHooks.GreenCardRequestNotification value)
{
if (value == null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "Parameter can't be null");
}
Logger.Log($"CarGreenCardController.Post - Debut {value.CorrelationId}");
string key = $"{value.CorrelationId}|{value.MessageId}";
// Save the notification for later processing
using (DAL.ApiDataContext ctx = new DAL.ApiDataContext())
{
ctx.CarGreenCardRequests.Add(new DAL.CarGreenCardRequest
{
RequestDate = DateTime.UtcNow,
RequestId = key,
RawRequest = JsonConvert.SerializeObject(value, Formatting.None),
});
ctx.SaveChanges();
}
// Creates a job that will be executed as soon as possible
_jobClient.Enqueue(() => ExecuteJob(key));
Logger.Log("CarGreenCardController.Post - Fin");
// Don't forget to notify AssurBox that the notication is received
return Request.CreateResponse(HttpStatusCode.OK, value.CorrelationId);
}
/// <summary>
/// Ici on va traiter la demande que l'on a sauvegardée
/// on récupère les infos
/// on crée une carte verte ou tout ce qu'on veut
/// et on envoie la réponse à AssurBox via l'api
/// </summary>
/// <param name="key"></param>
public void ExecuteJob(string key)
{
Logger.Log($"CarGreenCardController.ExecuteJob - Debut {key}");
// recherche dans la table
GreenCardRequestNotification assurBoxNotification;
using (DAL.ApiDataContext ctx = new DAL.ApiDataContext())
{
var request = ctx.CarGreenCardRequests.AsNoTracking().FirstOrDefault(x => x.RequestId == key);
assurBoxNotification = JsonConvert.DeserializeObject<SDK.WebHooks.GreenCardRequestNotification>(request.RawRequest);
}
switch (assurBoxNotification.NotificationType)
{
case SDK.WebHooks.GreenCardRequestNotificationTypes.InitialRequest:
{
// generates a sample green card and send it back to AssurBox
ProcessInitialRequest(key, assurBoxNotification);
}
break;
case SDK.WebHooks.GreenCardRequestNotificationTypes.Modification:
{
// generates a sample green card and send it back to AssurBox
ProcessModificationRequest(key, assurBoxNotification);
}
break;
case SDK.WebHooks.GreenCardRequestNotificationTypes.Cancelation:
{
ProcessCancellationRequest(key, assurBoxNotification);
}
break;
default: { } break;
}
}
/// <summary>
/// Handle a notification for a green card request
/// </summary>
/// <param name="key"></param>
/// <param name="assurBoxNotification"></param>
private void ProcessInitialRequest(string key, GreenCardRequestNotification assurBoxNotification)
{
// 1. retrieve a token to access the AssurBox Api
var tokenInfo = GetAssurBoxSecurityToken();
// 2. using the token, create a "greencard client"
CarGreenCardClient client = new CarGreenCardClient(new AssurBoxClientOptions { Host = Config.AssurBoxApiBaseURL, ApiKey = tokenInfo });
// 3. using the authentified client, retrieve the details of the green card request
// full detail about the customer, car information, ...
var requestDetails = client.GetRequest(assurBoxNotification.CorrelationId).Result;
// 4. do something with the request in your information system
var document = GetDemoPDF(requestDetails);
// 5. send a response to the requester, using the greencard client and a greencardrequestresponse object
GreenCardRequestResponse response = new GreenCardRequestResponse();
// The correlation id identify a greencard request file (this is mandatory)
response.CorrelationId = assurBoxNotification.CorrelationId;
// The messageid identify a specific message (this is mandatory)
response.MessageId = assurBoxNotification.MessageId;
string validationMessage = "";
if (ValidateRequest(assurBoxNotification, out validationMessage) == false)
{
// We can send a response refusing to issue a green card
response.HasApproval = false;
response.ApprovalReason = validationMessage;
response.ResponseContent = validationMessage;
}
else
{
// or we can send the green card back
response.HasApproval = true; // don't forget to set this property to true
// define a message for the requester
response.ResponseContent = $@"
Bonjour {assurBoxNotification.Requester.Name},
Merci pour votre demande, (type : {assurBoxNotification.NotificationType})
Voici votre carte pour {assurBoxNotification.LicencePlate}
Client : {requestDetails.CustomerName}
Bien à vous,
Assurance simulation demo ({requestDetails.InsuranceName})
";
// make sure the file is encoded as a base64 string
response.AddAttachment($"CarteVerte_{assurBoxNotification.LicencePlate}.pdf", Convert.ToBase64String(document));
}
// send the response to AssurBox
var resp = client.SendResponse(response).Result;
using (DAL.ApiDataContext ctx = new DAL.ApiDataContext())
{
var request = ctx.CarGreenCardRequests.FirstOrDefault(x => x.RequestId == key);
request.ResponseInfo = "Response sent " + resp.ResponseContent;
request.RequestRespondDate = DateTime.UtcNow;
ctx.SaveChanges();
}
}
private bool ValidateRequest(GreenCardRequestNotification assurBoxNotification, out string validationMessage)
{
// in order to test, we defined that "THROWERROR" in the communication should simulate a bad request
if (string.IsNullOrEmpty(assurBoxNotification.Communication) == false
&& assurBoxNotification.Communication.StartsWith("THROWERROR", StringComparison.InvariantCultureIgnoreCase))
{
validationMessage = "Validation Error : we can't issue a green card for this client.";
return false;
}
validationMessage = string.Empty;
return true;
}
/// <summary>
/// Handle a notification for a green card request
/// </summary>
/// <param name="key"></param>
/// <param name="assurBoxNotification"></param>
private void ProcessModificationRequest(string key, GreenCardRequestNotification assurBoxNotification)
{
// 1. retrieve a token to access the AssurBox Api
var tokenInfo = GetAssurBoxSecurityToken();
// 2. using the token, create a "greencard client"
CarGreenCardClient client = new CarGreenCardClient(new AssurBoxClientOptions { Host = Config.AssurBoxApiBaseURL, ApiKey = tokenInfo });
// 3. using the authentified client, retrieve the details of the green card request
// full detail about the customer, car information, ...
var requestDetails = client.GetRequest(assurBoxNotification.CorrelationId).Result;
// 4. do something with the request in your information system
var document = GetDemoPDFUpdate(requestDetails);
// 5. send a response to the requester, using the greencard client and a greencardrequestresponse object
GreenCardRequestResponse response = new GreenCardRequestResponse();
// The correlation id identify a greencard request file (this is mandatory)
response.CorrelationId = assurBoxNotification.CorrelationId;
// The messageid identify a specific message (this is mandatory)
response.MessageId = assurBoxNotification.MessageId;
response.HasApproval = true; // don't forget to set this property to true
// define a message for the requester
response.ResponseContent = $@"
Bonjour {assurBoxNotification.Requester.Name},
Merci pour votre demande, (type : {assurBoxNotification.NotificationType})
Voici votre carte mise à jour pour {assurBoxNotification.LicencePlate}
Client : {requestDetails.CustomerName}
Bien à vous,
Assurance simulation demo ({requestDetails.InsuranceName})
";
// make sure the file is encoded as a base64 string
response.AddAttachment($"CarteVerte_{assurBoxNotification.LicencePlate}.pdf", Convert.ToBase64String(document));
// send the response to AssurBox
var resp = client.SendResponse(response).Result;
using (DAL.ApiDataContext ctx = new DAL.ApiDataContext())
{
var request = ctx.CarGreenCardRequests.FirstOrDefault(x => x.RequestId == key);
request.ResponseInfo = "Updated response " + resp.ResponseContent;
request.RequestRespondDate = DateTime.UtcNow;
ctx.SaveChanges();
}
}
/// <summary>
/// Handle a notification that a Green card request is canceled
/// </summary>
/// <param name="key"></param>
/// <param name="assurBoxNotification"></param>
private void ProcessCancellationRequest(string key, GreenCardRequestNotification assurBoxNotification)
{
using (DAL.ApiDataContext ctx = new DAL.ApiDataContext())
{
var request = ctx.CarGreenCardRequests.FirstOrDefault(x => x.RequestId == key);
request.ResponseInfo = "The green card request was cancelled : " + assurBoxNotification.Communication;
request.RequestRespondDate = DateTime.UtcNow;
ctx.SaveChanges();
}
}
/// <summary>
/// Gets the JWT token to communicate with AssurBox
/// </summary>
/// <returns></returns>
private string GetAssurBoxSecurityToken()
{
string token = MemoryCache.Default["ABX_TOKEN"] as string;
if (string.IsNullOrEmpty(token))
{
SecurityClient id = new SecurityClient(new AssurBoxClientOptions { Host = Config.AssurBoxApiBaseURL });
var tokeninfo = id.GetBearerToken(Config.AssurBoxApiClientID, Config.AssurBoxApiClientSecret).Result;
token = tokeninfo.access_token;
MemoryCache.Default["ABX_TOKEN"] = token;
}
return token;
}
#region *** Remplissage simulation carte verte ***
private struct CarteVerteSimulationFields
{
public const string LicencePlate = "LicencePlate";
public const string VIN = "VIN";
public const string infos = "Other";
}
/// <summary>
/// Simulates a green card
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public byte[] GetDemoPDF(SDK.DTO.GreenCard.Car.GreenCardRequestInfo request)
{
string pdfSourcePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/cartevertetemplate.pdf");
using (var pdfReader = new PdfReader(pdfSourcePath))
{
var memoryStream = new MemoryStream();
var pdfStamper = new PdfStamper(pdfReader, memoryStream);
var pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField(CarteVerteSimulationFields.LicencePlate, request.LicencePlate);
pdfFormFields.SetField(CarteVerteSimulationFields.VIN, request.VIN);
string infos = "";
if (request.RequestDetails.Customer.IsCompany)
{
infos = $@"CREATION Preneur COMPANY : {request.RequestDetails.Customer.Company.Name}
Vehicule : {request.RequestDetails.CarDetails.Make} {request.RequestDetails.CarDetails.Model}
Généré le {DateTime.UtcNow} (UTC)
";
}
else
{
infos = $@"CREATION Preneur : {request.RequestDetails.Customer.Person.FirstName} {request.RequestDetails.Customer.Person.LastName}
Vehicule : {request.RequestDetails.CarDetails.Make} {request.RequestDetails.CarDetails.Model}
Généré le {DateTime.UtcNow} (UTC)
";
}
pdfFormFields.SetField(CarteVerteSimulationFields.infos, infos);//infos
pdfStamper.FormFlattening = false;
pdfStamper.Close();
return memoryStream.ToArray();
}
}
public byte[] GetDemoPDFUpdate(SDK.DTO.GreenCard.Car.GreenCardRequestInfo request)
{
string pdfSourcePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/cartevertetemplate.pdf");
using (var pdfReader = new PdfReader(pdfSourcePath))
{
var memoryStream = new MemoryStream();
var pdfStamper = new PdfStamper(pdfReader, memoryStream);
var pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField(CarteVerteSimulationFields.LicencePlate, request.LicencePlate);
pdfFormFields.SetField(CarteVerteSimulationFields.VIN, request.VIN);
string infos = $@"
UPDATE
Généré le {DateTime.UtcNow} (UTC)
";
pdfFormFields.SetField(CarteVerteSimulationFields.infos, infos);
pdfStamper.FormFlattening = false;
pdfStamper.Close();
return memoryStream.ToArray();
}
}
#endregion *** Remplissage simulation carte verte ***
}
}