-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcsv_processor.bal
More file actions
313 lines (294 loc) · 10.5 KB
/
csv_processor.bal
File metadata and controls
313 lines (294 loc) · 10.5 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
303
304
305
306
307
308
309
310
311
312
313
import ballerina/mime;
import ballerina/http;
import ballerina/io;
import ballerina/time;
import ballerina/regex;
function handleCSVBodyParts(http:Request request) returns string[][]|error {
var bodyParts = request.getBodyParts();
if (bodyParts is mime:Entity[]) {
string[][] csvLines = [];
foreach var bodyPart in bodyParts {
var mediaType = mime:getMediaType(bodyPart.getContentType());
if (mediaType is mime:MediaType) {
string baseType = mediaType.getBaseType();
if ("text/csv" == baseType) {
byte[] payload = check bodyPart.getByteArray();
csvLines = check getCSVData(payload);
} else {
return error("Invalid base type, not text/csv");
}
} else {
return error("Invalid media type");
}
}
return csvLines;
} else {
return error("Error in decoding multiparts!");
}
}
function getCSVData(byte[] payload) returns string[][]|error {
io:ReadableByteChannel readableByteChannel = check io:createReadableChannel(payload);
io:ReadableCharacterChannel readableCharacterChannel = new (readableByteChannel, "UTF-8");
io:ReadableCSVChannel readableCSVChannel = new io:ReadableCSVChannel(readableCharacterChannel, ",", 1);
return check channelReadCsv(readableCSVChannel);
}
function channelReadCsv(io:ReadableCSVChannel readableCSVChannel) returns string[][]|error {
string[][] results = [];
int i = 0;
while readableCSVChannel.hasNext() {
var records = readableCSVChannel.getNext();
if records is string[] {
results[i] = records;
i += 1;
} else if records is error {
check readableCSVChannel.close();
return records;
}
}
check readableCSVChannel.close();
return results;
}
function readMedicalNeedsCSVLine(string[] line, int csvLineNo) returns [string, int, string, string, string, string, string, string, int]|error => [
line[0],
check readIntCSVField(line[1], csvLineNo),
line[2],
line[3],
line[4],
line[5],
line[6],
line[7],
check readIntCSVField(line[8], csvLineNo)
];
function readSupplyQuotationsCSVLine(string[] line, int csvLineNo) returns [string, string, string, string, string, string, int, int, string, decimal]|error => [
line[0],
line[1],
line[2],
line[5],
line[6],
line[7],
check readIntCSVField(line[8], csvLineNo),
check readIntCSVField(line[8], csvLineNo),
line[9],
check readDollerCSVField(line[10], csvLineNo)
];
function readIntCSVField(string value, int csvLineNo) returns int|error {
int|error intVal = int:fromString(value.trim());
if (intVal is error) {
return error(string `Check line ${csvLineNo}, Unable to convert the value "${value}" to integer!`);
}
return intVal;
}
function readDollerCSVField(string value, int csvLineNo) returns decimal|error {
decimal|error decimalVal = decimal:fromString(value.substring(1, value.length()).trim());
if (decimalVal is error) {
return error(string `Check line ${csvLineNo}, Unable to convert doller amount:${value}`);
}
return decimalVal;
}
function getPeriod(string period) returns time:Date|error {
string[] dateParts = regex:split(period, " ");
int year = check int:fromString(dateParts[1]);
int month = check getMonth(dateParts[0]);
time:Date date = {year: year, month: month, day: 1};
return date;
}
function getMonth(string month) returns int|error {
match month {
"Jan" => {
return 1;
}
"Feb" => {
return 2;
}
"Mar" => {
return 3;
}
"Apr" => {
return 4;
}
"May" => {
return 5;
}
"Jun" => {
return 6;
}
"Jul" => {
return 7;
}
"Aug" => {
return 8;
}
"Sep" => {
return 9;
}
"Oct" => {
return 10;
}
"Nov" => {
return 11;
}
"Dec" => {
return 12;
}
_ => {
return error("Invalid month in the Period");
}
}
}
function getDateFromString(string dateString) returns time:Date|error {
string[] dateParts = regex:split(dateString, "/");
time:Date date = {
year: check int:fromString(dateParts[2]),
month: check int:fromString(dateParts[1]),
day: check int:fromString(dateParts[0])
};
return date;
}
function createMedicalNeedsFromCSVData(string[][] inputCSVData) returns MedicalNeed[]|error {
MedicalNeed[] medicalNeeds = [];
string errorMessages = "";
int csvLineNo = 0;
foreach var line in inputCSVData {
boolean hasError = false;
int medicalItemId = -1;
int medicalBeneficiaryId = -1;
csvLineNo += 1;
if (csvLineNo == 1) {
continue; // Medical needs csv has empty line at the beginning, skipping it.
}
if (line.length() == 9) {
var [_, _, urgency, period, beneficiary, itemName, itemType, unit, neededQuantity] = check readMedicalNeedsCSVLine(line, csvLineNo);
int|error itemID = createOrRetrieveMedicalItem(itemName, itemType, unit);
if itemID is error {
errorMessages = errorMessages + string `Line:${csvLineNo}| Error occurred while inserting ${itemName} into MEDICAL_ITEM table`;
hasError = true;
} else {
medicalItemId = itemID;
}
int|error beneficiaryID = getBeneficiaryId(beneficiary);
if (beneficiaryID is error) {
errorMessages = errorMessages + string `Line:${csvLineNo}| ${beneficiary} is missing in BENEFICIARY table`;
hasError = true;
} else {
medicalBeneficiaryId = beneficiaryID;
}
if (!hasError) {
MedicalNeed medicalNeed = {
itemID: medicalItemId,
beneficiaryID: medicalBeneficiaryId,
period: check getPeriod(period),
urgency,
neededQuantity
};
medicalNeeds.push(medicalNeed);
}
} else {
return error(string `Invalid CSV Length in line:${csvLineNo}`);
}
}
if (errorMessages.length() > 0) {
return error(errorMessages);
}
return medicalNeeds;
}
function createOrRetrieveMedicalItem(string itemName, string itemType, string unit) returns int|error {
int|error itemID = getMedicalItemId(itemName);
if itemID is int {
return itemID;
}
return addMedicalItemId(itemName, itemType, unit);
}
function createQuotationFromCSVData(string[][] inputCSVData) returns Quotation[]|error {
Quotation[] qutoations = [];
string errorMessages = "";
int csvLineNo = 0;
foreach var line in inputCSVData {
boolean hasError = false;
int medicalItemId = -1;
int quotationSupplierId = -1;
csvLineNo += 1;
if line.length() == 11 {
var [_, supplier, itemNeeded, regulatoryInfo, brandName, period, availableQuantity, remainingQuantity, expiryDate, unitPrice]
= check readSupplyQuotationsCSVLine(line, csvLineNo);
int|error itemID = getMedicalItemId(itemNeeded);
if (itemID is error) {
errorMessages = errorMessages + string `Line:${csvLineNo}| ${itemNeeded} is missing in MEDICAL_ITEM table`;
hasError = true;
} else {
medicalItemId = itemID;
}
int|error supplierID = getSupplierId(supplier);
if (supplierID is error) {
errorMessages = errorMessages + string `Line:${csvLineNo}| ${supplier} is missing in SUPPLIER table`;
hasError = true;
} else {
quotationSupplierId = supplierID;
}
if (!hasError) {
Quotation quotation = {
supplierID: quotationSupplierId,
itemID: medicalItemId,
brandName,
availableQuantity,
remainingQuantity,
period: check getPeriod(period),
expiryDate: check getDateFromString(expiryDate),
regulatoryInfo,
unitPrice
};
qutoations.push(quotation);
}
}
else {
return error(string `Invalid CSV Length in line:${csvLineNo}`);
}
}
if (errorMessages.length() > 0) {
return error(errorMessages);
}
return qutoations;
}
isolated function createSupplierFromCSVData(string[][] inputCsv) returns Supplier[]|error {
Supplier[] suppliers = [];
string[] errors = [];
foreach [int, string[]] [idx, line] in inputCsv.enumerate() {
int csvLineNo = idx + 1;
if line.length() != 4 {
return error(string `Invalid CSV Length in line:${csvLineNo}`);
}
var [name, shortName, email, phoneNumber] = readSupplierCsvLine(line);
boolean hasErrors = false;
if !isValidEmail(email) {
errors.push(string `Line:${csvLineNo}| provided email [${email}] is invalid`);
hasErrors = true;
}
phoneNumber = regex:replaceAll(phoneNumber, "\\s+", "");
if !isValidPhoneNumber(phoneNumber) {
errors.push(string `Line:${csvLineNo}| provided phone number [${phoneNumber}] is invalid`);
hasErrors = true;
}
if !hasErrors {
Supplier supplier = {
name: name,
shortName: shortName,
email: email,
phoneNumber: phoneNumber
};
suppliers.push(supplier);
}
}
if errors.length() > 0 {
string errorMsg = string:'join(",", ...errors);
return error (errorMsg);
}
return suppliers;
}
isolated function readSupplierCsvLine(string[] line) returns string[4] => [line[0], line[1], line[2], line[3]];
final string emailRegex = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";
isolated function isValidEmail(string email) returns boolean {
return regex:matches(email, emailRegex);
}
final string phoneNumberRegex = "\\+[1-9]{1}[0-9]{3,14}";
isolated function isValidPhoneNumber(string phoneNumber) returns boolean {
return regex:matches(phoneNumber, phoneNumberRegex);
}