-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInvoiceService.cs
More file actions
302 lines (275 loc) · 13.3 KB
/
InvoiceService.cs
File metadata and controls
302 lines (275 loc) · 13.3 KB
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
using Volo.Abp;
using System.Net;
using System.Threading.Tasks;
using System.Text.Json;
using System;
using Unity.Payments.Integrations.Http;
using Volo.Abp.Application.Services;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using Unity.Payments.Enums;
using Unity.Payments.Domain.Suppliers;
using Unity.Payments.Domain.PaymentRequests;
using Volo.Abp.DependencyInjection;
using Unity.Payments.Codes;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Volo.Abp.Uow;
using Unity.Modules.Shared.Http;
using Unity.Payments.PaymentConfigurations;
using Unity.Payments.Domain.AccountCodings;
namespace Unity.Payments.Integrations.Cas
{
[IntegrationService]
[ExposeServices(typeof(InvoiceService), typeof(IInvoiceService))]
#pragma warning disable S107 // Methods should not have too many parameters
public class InvoiceService(
ICasTokenService iTokenService,
IAccountCodingRepository accountCodingRepository,
PaymentConfigurationAppService paymentConfigurationAppService,
IPaymentRequestRepository paymentRequestRepository,
IResilientHttpRequest resilientHttpRequest,
IOptions<CasClientOptions> casClientOptions,
ISupplierRepository iSupplierRepository,
ISiteRepository iSiteRepository,
IUnitOfWorkManager unitOfWorkManager) : ApplicationService, IInvoiceService
#pragma warning restore S107 // Methods should not have too many parameters
{
private const string CFS_APINVOICE = "cfs/apinvoice";
private readonly Dictionary<int, string> CASPaymentGroup = new()
{
[(int)PaymentGroup.EFT] = "GEN EFT",
[(int)PaymentGroup.Cheque] = "GEN CHQ"
};
protected virtual async Task<Invoice?> InitializeCASInvoice(PaymentRequest paymentRequest,
string? accountDistributionCode)
{
Invoice? casInvoice = new();
Site? site = await GetSiteByPaymentRequestAsync(paymentRequest);
if (site != null && site.Supplier != null && site.Supplier.Number != null && accountDistributionCode != null)
{
// This can not be UTC Now it is sent to cas and can not be in the future - this is not being stored in Unity as a date
var vancouverTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, vancouverTimeZone);
var currentMonth = localDateTime.ToString("MMM").Trim('.');
var currentDay = localDateTime.ToString("dd");
var currentYear = localDateTime.ToString("yyyy");
var dateStringDayMonYear = $"{currentDay}-{currentMonth}-{currentYear}";
casInvoice.SupplierNumber = site.Supplier.Number; // This is from each Applicant
casInvoice.SupplierName = site.Supplier.Name;
casInvoice.SupplierSiteNumber = site.Number;
casInvoice.PayGroup = CASPaymentGroup[(int)site.PaymentGroup]; // GEN CHQ - other options
casInvoice.InvoiceNumber = paymentRequest.InvoiceNumber;
casInvoice.InvoiceDate = dateStringDayMonYear; //DD-MMM-YYYY
casInvoice.DateInvoiceReceived = dateStringDayMonYear;
casInvoice.GlDate = dateStringDayMonYear;
casInvoice.InvoiceAmount = paymentRequest.Amount;
casInvoice.InvoiceBatchName = paymentRequest.BatchName;
casInvoice.PaymentAdviceComments = paymentRequest.Description;
InvoiceLineDetail invoiceLineDetail = new()
{
InvoiceLineNumber = 1,
InvoiceLineAmount = paymentRequest.Amount,
DefaultDistributionAccount = accountDistributionCode // This will be at the tenant level
};
casInvoice.InvoiceLineDetails = new List<InvoiceLineDetail> { invoiceLineDetail };
}
return casInvoice;
}
public async Task<Site?> GetSiteByPaymentRequestAsync(PaymentRequest paymentRequest)
{
Site? site = await iSiteRepository.GetAsync(paymentRequest.SiteId, true);
if (site?.SupplierId != null)
{
Supplier supplier = await iSupplierRepository.GetAsync(site.SupplierId);
site.Supplier = supplier;
}
return site;
}
public async Task<InvoiceResponse?> CreateInvoiceByPaymentRequestAsync(string invoiceNumber)
{
InvoiceResponse invoiceResponse = new();
try
{
PaymentRequest? paymentRequest = await paymentRequestRepository.GetPaymentRequestByInvoiceNumber(invoiceNumber);
if (paymentRequest is null)
{
throw new UserFriendlyException("CreateInvoiceByPaymentRequestAsync: Payment Request not found");
}
if (!paymentRequest.AccountCodingId.HasValue)
{
throw new UserFriendlyException("CreateInvoiceByPaymentRequestAsync: Account Coding - Payment Request - not found");
}
AccountCoding accountCoding = await accountCodingRepository.GetAsync(paymentRequest.AccountCodingId.Value);
string accountDistributionCode = await paymentConfigurationAppService.GetAccountDistributionCode(accountCoding);// this will be on the payment request
if (!string.IsNullOrEmpty(accountDistributionCode))
{
Invoice? invoice = await InitializeCASInvoice(paymentRequest, accountDistributionCode);
if (invoice is not null)
{
invoiceResponse = await CreateInvoiceAsync(invoice);
if (invoiceResponse is not null)
{
await UpdatePaymentRequestWithInvoice(paymentRequest.Id, invoiceResponse);
}
}
}
}
catch (Exception ex)
{
string ExceptionMessage = ex.Message;
Logger.LogError(ex, "CreateInvoiceByPaymentRequestAsync Exception: {ExceptionMessage}", ExceptionMessage);
}
return invoiceResponse;
}
private async Task UpdatePaymentRequestWithInvoice(Guid paymentRequestId, InvoiceResponse invoiceResponse)
{
try
{
using var uow = unitOfWorkManager.Begin();
PaymentRequest? paymentRequest = await paymentRequestRepository.GetAsync(paymentRequestId);
paymentRequest.SetCasHttpStatusCode((int)invoiceResponse.CASHttpStatusCode);
paymentRequest.SetCasResponse(invoiceResponse.CASReturnedMessages);
// Set the status - for the payment request
if (invoiceResponse.IsSuccess())
{
paymentRequest.SetInvoiceStatus(CasPaymentRequestStatus.SentToCas);
}
else
{
paymentRequest.SetInvoiceStatus(CasPaymentRequestStatus.ErrorFromCas);
}
await paymentRequestRepository.UpdateAsync(paymentRequest, autoSave: false);
await uow.SaveChangesAsync();
}
catch (Exception ex)
{
string ExceptionMessage = ex.Message;
Logger.LogError(ex, "CreateInvoiceByPaymentRequestAsync Exception: {ExceptionMessage}", ExceptionMessage);
}
}
public async Task<InvoiceResponse> CreateInvoiceAsync(Invoice casAPInvoice)
{
string jsonString = JsonSerializer.Serialize(casAPInvoice);
var authToken = await iTokenService.GetAuthTokenAsync();
var resource = $"{casClientOptions.Value.CasBaseUrl}/{CFS_APINVOICE}/";
var response = await resilientHttpRequest.HttpAsyncWithBody(HttpMethod.Post, resource, jsonString, authToken);
if (response != null)
{
if (response.Content != null && response.StatusCode != HttpStatusCode.NotFound)
{
var contentString = ResilientHttpRequest.ContentToString(response.Content);
var result = JsonSerializer.Deserialize<InvoiceResponse>(contentString)
?? throw new UserFriendlyException("CAS InvoiceService CreateInvoiceAsync Exception: " + response);
result.CASHttpStatusCode = response.StatusCode;
return result;
}
else if (response.RequestMessage != null)
{
throw new UserFriendlyException("CAS InvoiceService CreateInvoiceAsync Exception: " + response.RequestMessage);
}
else
{
throw new UserFriendlyException("CAS InvoiceService CreateInvoiceAsync Exception: " + response);
}
}
else
{
throw new UserFriendlyException("CAS InvoiceService CreateInvoiceAsync: Null response");
}
}
public async Task<CasPaymentSearchResult> GetCasInvoiceAsync(string invoiceNumber, string supplierNumber, string supplierSiteCode)
{
var authToken = await iTokenService.GetAuthTokenAsync();
var resource = $"{casClientOptions.Value.CasBaseUrl}/{CFS_APINVOICE}/{invoiceNumber}/{supplierNumber}/{supplierSiteCode}";
var response = await resilientHttpRequest.HttpAsync(HttpMethod.Get, resource, authToken);
if (response != null
&& response.Content != null
&& response.IsSuccessStatusCode)
{
string contentString = ResilientHttpRequest.ContentToString(response.Content);
var result = JsonSerializer.Deserialize<CasPaymentSearchResult>(contentString);
return result ?? new CasPaymentSearchResult();
}
else
{
return new CasPaymentSearchResult() { };
}
}
public async Task<CasPaymentSearchResult> GetCasPaymentAsync(string invoiceNumber, string supplierNumber, string siteNumber)
{
var authToken = await iTokenService.GetAuthTokenAsync();
var resource = $"{casClientOptions.Value.CasBaseUrl}/{CFS_APINVOICE}/{invoiceNumber}/{supplierNumber}/{siteNumber}";
var response = await resilientHttpRequest.HttpAsync(HttpMethod.Get, resource, authToken);
CasPaymentSearchResult casPaymentSearchResult = new();
if (response != null
&& response.Content != null
&& response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<CasPaymentSearchResult>(content.Result);
return result ?? casPaymentSearchResult;
}
else if (response != null)
{
casPaymentSearchResult.InvoiceStatus = response.StatusCode.ToString();
}
return casPaymentSearchResult;
}
}
#pragma warning disable S125 // Sections of code should not be commented out
/*
<INVOICE NUMBER>/<SUPPLIER NUMBER>/<SUPPLIER SITE CODE>
Example Response for GET:
{
"invoice_number": "TESTINVOICE2",
"invoice_status": "Validated",
"payment_status": " Paid",
"payment_number": "009877676",
"payment_date": "25-Aug-2017"
}
Void Payment Webservices Request Format, Type POST
https://<server>:<port>/ords/cas/cfs/apinvoice/
Sample JSON File – Regular Standard Invoice - Web Service
{
"invoiceType": "Standard",
"supplierNumber": "3125635",
"supplierSiteNumber": "001",
"invoiceDate": "06-MAR-2023", ---
"invoiceNumber": "CAETEST0B",
"invoiceAmount": 150.00,
"payGroup": "GEN CHQ", -- COULD BE GEN EFT
"dateInvoiceReceived":"02-MAR-2023", ---
"dateGoodsReceived": "01-MAR-2023",
"remittanceCode": "01", -- Refers to Invoice Number in Remmitance
"specialHandling": "N",
"nameLine1": "",
"nameLine2": "",
"qualifiedReceiver": "",
"terms": "Immediate",
"payAloneFlag": "Y",
"paymentAdviceComments": "Test",
"remittanceMessage1": "",
"remittanceMessage2": "",
"remittanceMessage3": "",
"glDate": "06-MAR-2023",
"invoiceBatchName": "CASAPWEB1",
"currencyCode": "CAD",
"invoiceLineDetails":
[{
"invoiceLineNumber": 1,
"invoiceLineType": "Item",
"lineCode": "DR",
"invoiceLineAmount": 150.00,
"defaultDistributionAccount": "039.15006.10120.5185.1500000.000000.0000",
"description": "Test Line Description",
"taxClassificationCode": "",
"distributionSupplier": "",
"info1": "",
"info2": "",
"info3": ""
}]
}
*/
#pragma warning restore S125 // Sections of code should not be commented out
}