Merge: Added contributing guidelines and link from readme
[nit.git] / contrib / refund / src / refund_json.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2015 Alexandre Terrasa <alexandre@moz-code.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # JSON handling for `refund`.
18 module refund_json
19
20 import refund_base
21 import json::static
22
23 redef class RefundProcessor
24
25 redef fun process(input_file, output_file) do
26 self.output_file = output_file
27 var json = load_input(input_file)
28 var sheet = new ReclamationSheet.from_json(self, json)
29 var res = process_refunds(sheet)
30 write_output(res.to_pretty_json, output_file)
31 end
32
33 # Computes allowed refunds for a given `ReclamationSheet`.
34 fun process_refunds(sheet: ReclamationSheet): JsonObject do
35 # update stats
36 var stats = load_stats
37 stats.inc("total_treatments")
38 # compute refunds
39 current_refunds.clear
40 var json = new JsonObject
41 json["dossier"] = sheet.file.to_s
42 json["mois"] = sheet.month.to_s
43 var arr = new JsonArray
44 var sum = 0.0.to_dollar
45 for recl in sheet.recls do
46 var refund = process_refund(sheet, recl)
47 var obj = new JsonObject
48 obj["soin"] = recl.care_id
49 obj["date"] = recl.date.to_s
50 obj["montant"] = refund.to_s
51 arr.add obj
52 sum += refund
53 # update stats for care
54 stats.inc("total_{recl.care_id}")
55 end
56 save_stats(stats)
57 json["remboursements"] = arr
58 json["total"] = sum.to_s
59 return json
60 end
61
62 # Loads the input string and returns its content as a JsonObject.
63 #
64 # Dies if the file cannot be read or does not contain a valid JSONObject.
65 fun load_input(file: String): JsonObject do
66 if not file.file_exists then
67 die("File `{file}` not found.")
68 abort
69 end
70 var ptr = new FileReader.open(file)
71 var json = ptr.read_all.parse_json
72 if json isa JsonParseError then
73 die("Wrong input file ({json.message})")
74 abort
75 else if json == null then
76 die("Unable to parse input file as json (got null)")
77 abort
78 else if not json isa JsonObject then
79 die("Wrong input type (expected JsonObject got {json.class_name})")
80 abort
81 end
82 ptr.close
83 return json
84 end
85
86 # Writes `str` in path specified by `file`.
87 #
88 # Used to produce output and stats.
89 fun write_output(str: String, file: String) do
90 var ofs = new FileWriter.open(file)
91 ofs.write(str)
92 ofs.close
93 end
94
95 # UTILS
96
97 # Does `json` contains `key`? Dies otherwise.
98 private fun check_key(json: JsonObject, key: String) do
99 if json.has_key(key) then return
100 die("Malformed input (missing key {key})")
101 end
102
103 # Does `str` match the regex `re`.
104 private fun check_format(str, re: String): Bool do
105 return str.has(re.to_re)
106 end
107
108 redef fun die(msg) do
109 # save error
110 var obj = new JsonObject
111 obj["message"] = msg
112 write_output(obj.to_pretty_json, output_file)
113 # update stats
114 var stats = load_stats
115 stats.inc("total_reject")
116 save_stats(stats)
117 # leave
118 exit 1
119 end
120
121 redef fun show_stats do print load_stats.to_json.to_pretty_json
122
123 redef fun load_stats do
124 # If no stats found, return a new object
125 if not stats_file.file_exists then return new RefundStats
126 # Try to read from file
127 var ifs = new FileReader.open(stats_file)
128 var content = ifs.read_all.parse_json
129 ifs.close
130 # If file is corrupted, return a new object
131 if not content isa JsonObject then return new RefundStats
132 # Return file contained stats
133 return new RefundStats.from_json(content)
134 end
135
136 redef fun save_stats(stats) do
137 write_output(stats.to_json.to_pretty_json, stats_file)
138 end
139 end
140
141 redef class RefundStats
142
143 # Inits `self` from the content of a JsonObject
144 init from_json(json: JsonObject) do
145 for k, v in json do self[k] = v.as(Int)
146 end
147
148 # Outputs `self` as a JSON string.
149 fun to_json: JsonObject do
150 var obj = new JsonObject
151 for k, v in self do obj[k] = v
152 return obj
153 end
154 end
155
156 redef class ReclamationSheet
157
158 # Inits `self` from the content of a `JsonObject`.
159 init from_json(proc: RefundProcessor, json: JsonObject) do
160 file = new ReclFile.from_json(proc, json)
161 month = new ReclMonth.from_json(proc, json)
162 recls = parse_recls(proc, json)
163 init(file, month)
164 end
165
166 # Parses and checks the given `json` then returns an array of `Reclamation` instances.
167 private fun parse_recls(proc: RefundProcessor, json: JsonObject): Array[Reclamation] do
168 proc.check_key(json, "reclamations")
169 var res = new Array[Reclamation]
170 var recls = json["reclamations"]
171 if recls == null then
172 proc.die("Wrong type for `number` (expected JsonArray got null)")
173 abort
174 else if not recls isa JsonArray then
175 proc.die("Wrong type for `number` (expected JsonArray got {recls.class_name})")
176 abort
177 end
178 var i = 0
179 for obj in recls do
180 if obj == null then
181 proc.die("Wrong type for `reclamations#{i}` (expected JsonObject got null)")
182 abort
183 else if not obj isa JsonObject then
184 proc.die("Wrong type for `reclamations#{i}` " +
185 "(expected JsonObject got {obj.class_name})")
186 abort
187 end
188 var recl = new Reclamation.from_json(proc, obj)
189 if not month.has(recl.date) then
190 proc.die("Wrong `mois` for `soin` with id `{recl.care_id}`")
191 abort
192 end
193 if file.contract.care_by_id(recl.care_id) == null then
194 proc.die("Unknown `soin` with id `{recl.care_id}`")
195 abort
196 end
197 res.add recl
198 i += 1
199 end
200 return res
201 end
202 end
203
204 redef class ReclFile
205 # Inits `self` from the content of a JsonObject.
206 init from_json(proc: RefundProcessor, json: JsonObject) do
207 proc.check_key(json, "dossier")
208 var id = json["dossier"]
209 if id == null then
210 proc.die("Wrong type for `dossier` (expected String got null)")
211 abort
212 else if not id isa String then
213 proc.die("Wrong type for `dossier` (expected String got {id.class_name})")
214 abort
215 end
216 # Check format
217 parse_contract(proc, id)
218 parse_client(proc, id)
219 init(id)
220 end
221
222 # Tries to parse the contract from `file_id` string.
223 private fun parse_contract(proc: RefundProcessor, file_id: String) do
224 var kind = file_id.first.to_s
225 if not proc.check_format(kind, "^[A-E]\{1\}$") then
226 proc.die("Wrong contract (expected A, B, C, D or E got {kind})")
227 end
228 contract = contract_factory(proc, kind)
229 end
230
231 # Tries to parse the client number from the `file_id` string.
232 private fun parse_client(proc: RefundProcessor, file_id: String) do
233 var num = file_id.substring_from(1)
234 if not proc.check_format(num, "^[0-9]\{6\}$") then
235 proc.die("Wrong format for `number` (expected XXXXXX got {num})")
236 abort
237 end
238 client = new Client(num)
239 end
240 end
241
242 redef class ReclMonth
243 # Inits `self` from a `JsonObject`.
244 init from_json(proc: RefundProcessor, json: JsonObject) do
245 proc.check_key(json, "mois")
246 var month = json["mois"]
247 if month == null then
248 proc.die("Wrong type for `mois` (expected String got null)")
249 return
250 else if not month isa String then
251 proc.die("Wrong type for `mois` (expected String got {month.class_name})")
252 return
253 end
254 if not proc.check_format(month, "^[0-9]\{4\}-[0-9]\{2\}$") then
255 proc.die("Wrong format for `mois` (expected AAAA-MM got {month})")
256 return
257 end
258 from_string(proc, month)
259 end
260
261 # Inits `self` from a string representation formatted as `AAAA-MM`.
262 init from_string(proc: RefundProcessor, str: String) do
263 var parts = str.split("-")
264 var year = parts[0].to_i
265 var month = parts[1].to_i
266 if month < 1 or month > 12 then
267 proc.die("Wrong format for `mois` (expected AAAA-MM got {str})")
268 return
269 end
270 date = new ReclDate(year, month, 1)
271 init(date)
272 end
273 end
274
275 redef class ReclDate
276 # Inits `self` from a `JsonObject`.
277 #
278 # Dies if the `json` input is invalid.
279 init from_json(proc: RefundProcessor, json: JsonObject) do
280 proc.check_key(json, "date")
281 var date = json["date"]
282 if date == null then
283 proc.die("Wrong type for `date` (expected String got null)")
284 abort
285 else if not date isa String then
286 proc.die("Wrong type for `date` (expected String got {date.class_name})")
287 abort
288 end
289 if not proc.check_format(date, "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}$") then
290 proc.die("Wrong format for `date` (expected AAAA-MM-DD got {date})")
291 abort
292 end
293 from_string(proc, date)
294 end
295
296 # Inits `self` from its string representation formatted as `AAAA-MM`.
297 init from_string(proc: RefundProcessor, str: String) do
298 var parts = str.split("-")
299 year = parts[0].to_i
300 month = parts[1].to_i
301 day = parts[2].to_i
302 if month < 1 or month > 12 or day < 1 or day > 31 then
303 proc.die("Wrong format for `mois` (expected AAAA-MM got {str})")
304 abort
305 end
306 init(year, month, day)
307 end
308 end
309
310 redef class Reclamation
311 # Inits `self` from a `JsonObject`.
312 init from_json(proc: RefundProcessor, json: JsonObject) do
313 care_id = parse_care_id(proc, json)
314 date = new ReclDate.from_json(proc, json)
315 fees = parse_fees(proc, json)
316 init(care_id, date, fees)
317 end
318
319 # Inits `self` from its string representation formatted as `Int`.
320 private fun parse_care_id(proc: RefundProcessor, json: JsonObject): Int do
321 proc.check_key(json, "soin")
322 var id = json["soin"]
323 if id == null then
324 proc.die("Wrong type for `soin` (expected Int got null)")
325 abort
326 else if not id isa Int then
327 proc.die("Wrong type for `soin` (expected Int got {id.class_name})")
328 abort
329 end
330 return id
331 end
332
333 # Inits `self` from its string representation formatted as `0.00$`.
334 private fun parse_fees(proc: RefundProcessor, json: JsonObject): Dollar do
335 proc.check_key(json, "montant")
336 var fees = json["montant"]
337 if fees == null then
338 proc.die("Wrong type for `fees` (expected String got null)")
339 abort
340 else if not fees isa String then
341 proc.die("Wrong type for `fees` (expected String got {fees.class_name})")
342 abort
343 end
344 if not proc.check_format(fees, "^[0-9]+((\\.|\\,)[0-9]+)?\\$$") then
345 proc.die("Wrong format for `montant` (expected XX.XX$ got {fees})")
346 abort
347 end
348 return new Dollar.from_float(fees.basename("$").to_f)
349 end
350 end